Pillo
Pillo

Reputation: 357

How can i pass parameters from method to action in vuejs vuex

I have to files with this code:

Users.vue

methods: {
obtenerUsuarios() {
  console.log('Obtener Usuarios')
  this.$store
    .dispatch('auth/getValidToken')
    .then((data) => {
      console.log(data). // Console First Message
      this.$store
        .dispatch('user/fetchUsers', data)
        .then((response) => {
          this.items = response.data
        })
        .catch((error) => {
          console.log(error)
        })
    })
    .catch((error) => {
      console.log('Error: ' + error)
    })
},

},

Console Firsts Mesagge show me a json web token in console that is ok. When i dispatch 'user/fetchUsers in

user.js

export const actions = {
    fetchUsers({ jwt }) {
    console.log('Action JWT:' + jwt)  //Second console.log
    return UserService.getUsers(jwt)
  },
}

The second messaje show me: Action JWT:undefined in the console

if i change the line two to

fetchUsers(jwt) {

The second messaje show me: Action JwT:[object Object]

I need to pass a json web token from Users.vue method to fetchUsers action y user.js

I will to appreciate any help

Jose Rodriguez

Upvotes: 0

Views: 463

Answers (1)

tony19
tony19

Reputation: 138656

Your action method currently declares the data in the first argument (and no second argument), but actions receive the Vuex context as its first argument. The data payload is in the second argument:

const actions = {
  //fetchUsers(data) {}        // DON'T DO THIS (1st arg is for context)
  fetchUsers(context, data) {}
}

Upvotes: 2

Related Questions