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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With