1
votes

I have backend Laravel API where i get

{
"id": 1,
"name": "Toni Stoyanov",
"email": "[email protected]"
},

"id": 2,
"name": "Thomas Shelby",
"email": "[email protected]"
}
]

In my routes in Vue :

 {
  path: '/users/:id',
  component: UserDetails,
  props:true
},

I want to Display every single user for example with users/1 i want to get my first record from API.

In Vuex state i have :

namespaced: true,
    state(){
        return{
            users: {
              
            }
        }
    },

getters:

getUsers(state){
        return state.users
    }

mutations:

SET_USER(state, data){
        state.users = data
    }

and this action where i fetch all users:

async setUsers(context){
        let response = await axios.get('users/all')

        context.commit('SET_USER',response.data)
    }

In my DisplayUser.vue i have :

props:['id'],
    data(){
        return{
            selectedUser: null
        }
    },
    created(){
       this.$store.dispatch('users/setUsers')

        this.selectedUser = this.$store.getters['users/getUsers'].find(user => user.id === this.id);
    },

First i dispatch my action to get data from API and after that in selectedUsers try to find the same id user..but in console i get

this.$store.getters['users/getUsers'].find is not a function.

If i set in users static data everything works sometimes! But when i fetch them from API no.

1

1 Answers

3
votes

You're trying to access the getter before the http request has completed. It should be enough to wait for the promise in created.

The prop is a string

Also, the prop is coming as a string, so a === will not match. You can cast it to a Number(this.id) first:

Using .then syntax:

created(){
  this.$store.dispatch('users/setUsers').then(res => {
    this.selectedUser = this.$store.getters['users/getUsers'].find(user => user.id === Number(this.id));
  });
}

Or using async/await syntax:

async created(){   // async keyword
  await this.$store.dispatch('users/setUsers')   // await this
  this.selectedUser = this.$store.getters['users/getUsers'].find(user => user.id === Number(this.id));
}