How to pass dynamic parameter (ID) to axios api call?

fdR picture fdR · Sep 9, 2019 · Viewed 7.3k times · Source

I have an api with the last part dynamic: src/api/user.js

export function getProfileData() {
  return request({
    url: 'http://localhost:8000/profile_update/DYNAMIC USER ID HERE',
    method: 'get',
  })
}

I am calling this api in this action: store/modules/user.js

setProfileData({ commit }) {
 return getProfileData(userId).then(response => {
 console.log('RESPONSE setProfileData action dispatch', response)
 commit('SET_PROFILE_DATA', response.results)
})

(In this module I also have state and mutations - working) This action is dispatched here: src/views/users-list

goToUserProfile(user) {
  const userId = user.id
  this.$store.dispatch('user/setCurrentUser').then(() => {
    const profileData = this.$store.dispatch('user/setProfileData(userId)').then(() => {
      const profileData = this.$store.getters.profileData
      this.profileData = profileData
      console.log('users-list sending profile data: ', profileData )
      this.$router.push({
        name: 'SeeUserProfile',
        params: {
        userId: userId
      } 
    })
  }).catch((err) => {
     console.log('ERROR IN fetchin' userDataProfile: ', err)
     this.loading = false
   })
 })
}

The argument user comes from

@click.prevent="goToUserProfile(data.item), selectUser(data.item)"

So data.item = single selected user

This code is not working. I need the dynamic user id to be used in the api. In the store I also have:

setCurrentUser({ commit }, userData) {
commit('SET_CURRENT_USER', userData)}

which is working fine -inside userData there is the property id.

I tried using /${params.userId}, but how do I pass this in the api?

How do I pass the userId to the axios call? Hope I’ve been clear. I’ve extracted very much the code, so if needed I will post all of it.

Answer

glitch picture glitch · Sep 9, 2019
  • Add the id parameter for the getProfileData function getProfileData(usedId) and include it in the url: url: http://localhost:8000/profile_update/${ DYNAMIC USER ID HERE } (remember to enclose the link with backticks)
  • Add the id parameter for the setProfileData function: setProfileData({ commit }, userId)
  • If the id will be a route params, extract it using this.$route.params.userId

Hope this helps.

Use the backtips for the entire url instead of double quotes, and it works.