简体   繁体   中英

Pass id from Vue router param to component's Vuex dispatch

I have backend Laravel API where i get

{
"id": 1,
"name": "Toni Stoyanov",
"email": "toni.nikolaev.23@gmail.com"
},

"id": 2,
"name": "Thomas Shelby",
"email": "st3851ba@gmail.com"
}
]

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.

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM