0
votes

I have created a component for the user profile. JSON data is coming from Laravel JWT authentication. But getting

TypeError: Cannot read property 'id' of undefined. same for the name also

<template>
  <div class="mt-3">
        <div class="alert alert-danger" v-if="has_error">
          <p>Something goes wrong</p>
        </div>
      <p>{{ user.id }}</p>
      <p>{{ user.name }}</p>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        has_error: false,
        user:{
          id:'',
          name:''
        }
      }
    },
    mounted() {
      this.getUsers()
    },
    methods: {
      getUsers() {
        this.$http({
          url: `auth/profile`,
          method: 'GET'
        })
            .then((res) => {
              this.user = res.data.user
            }, () => {
              this.has_error = true
            })
      }
    }
  }
</script>

Actual results must be: 1 Username

2
try a console.log(this.user) to be sure it returns id - codervine
res.data.user is what is causing trouble. console.log(res.data) and confirm you are receiving user from the API. - Thomas Van der Veen
Thanks, consol.log(res.data) is providing a correct object..how to display this object property? - Sk Md Nurujjaman
Done, Thanks Codervine and Thomas - Sk Md Nurujjaman

2 Answers

0
votes

So, you properly defined user in component data. And the error you are getting might happen only in the case if res.data.user is undefined which you are getting from API in getUsers method. I suggest, there is no user object in response data. By that way res.data.user is undefined and as you reasigned this.user to be equal res.data.user it get undefined value too.

0
votes

Instead of "this.user = res.data.user" we have to wight "this.user = res.data". And this solved this problem.