Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alpine Expression Error: Cannot read properties of undefined (reading 'name') Expression: "user.company.name"

Tags:

alpine.js

please am new to Alpine js and I don't know what am getting wrong, am making a request to https://jsonplaceholder.typicode.com/users/1 and storing the JSON response to user. am able to access the user with x-text but get an error when I try to access an object within the user object

this is my js and html

Alpine Expression Error: Cannot read properties of undefined (reading 'name') Expression: "user.company.name"

Uncaught TypeError: Cannot read properties of undefined (reading 'name') at eval (eval at

  function data() {
         return {
             user: '',
             data() {
                 fetch('https://jsonplaceholder.typicode.com/users/1')
                     .then(response => response.json())
                     .then(json => this.user = json)
             },
         }
     }
<div x-data="data()" x-init="initData()">
  <span x-text="user.company.name"></span>
</div>
like image 522
Phill Avatar asked Oct 30 '25 19:10

Phill


1 Answers

This is because user is empty on pageload. Your data has not been processed yet. Use optional chaining:

user?.company?.name; // Results in 'undefined' before data is loaded
user?.company?.name || 'placeholder'; // Results in "placeholder" before data is loaded

Once your data is loaded and user is populated, your x-text should display accordingly

like image 69
Yinci Avatar answered Nov 02 '25 11:11

Yinci