Arpad Gabor
Arpad Gabor

Reputation: 15278

Get request yields response with data in it, but when accessing .data specifically it yields undefined

Apologies if the terminology is not great, still new to fullstack.

Hello! I am trying to get all the users in my DB. The get() response is OK as the client is receiving the response (see image below)

Response is OK, data is undefined

The problem is that when I try to fetch the .data I get undefined.

Here's my Vue Component

import UserService from '@/services/UsersService.js'

export default {
  data () {
    return {
      users: null
    }
  },
  async mounted () {
    // GET request for all users.
    this.users = UserService.index().data
    console.log('The response is OK', await UserService.index())
    console.log('when trying to fetch the .data I am getting  ', await this.users)
  }
}

The index() function

import Api from '@/services/Api'

export default {
  index () {
    return Api().get('users')
  }
}

Everything works fine, except that I get undefined data...

Upvotes: 0

Views: 25

Answers (1)

Derek Nguyen
Derek Nguyen

Reputation: 11577

I think you forgot to fetch the data asynchronously?

  async mounted () {
    // GET request for all users.

-   this.users = UserService.index().data
+   const res = await UserService.index()
+   this.users = res.data

    console.log('The response is OK', await UserService.index())
    console.log('when trying to fetch the .data I am getting  ', await this.users)
}

You correctly use await syntax in the first console.log, which might explain why the data return correctly.

Upvotes: 1

Related Questions