feli
feli

Reputation: 11

How to get access to store from action in VueJS?

Im using VueJS and Vuex. I have the userid into the store, this way: vuex screenshot

And i try pass the userid to a fetch, but vuejs return error

([Vue warn]: Error in created hook: "TypeError: this.$store is undefined")

import { LOAD_APPOINTMENTS } from './types'

export default {
  loadProducts ({ commit }) {
    var user = this.$store.state.user.userid
    fetch('api/appointments/' + user)
      .then((result) => {
        return result.json()
      })
      .then((appointments) => {
        commit(LOAD_APPOINTMENTS, appointments)
      })
      .catch(er => {
        console.log(er)
      })
  }
}

Upvotes: 0

Views: 2295

Answers (1)

T.Woody
T.Woody

Reputation: 1228

First, when referencing the store within vuex files:

  1. context.state instead of this.$store.state.
  2. context for all of the this.$store. So, context.commit and context.dispatch.

Second, the loadProducts needs to be rewritten as an action per docs.

Third, loadProducts needs to incorporate the context as a parameter:

actions: {
  loadProducts (context) {
    ...
    context.commit(...)
    ...
  }
}

As @phil has mentioned in this thread, it is important to view the documentation entirely, as this single answer will get you on the way to debugging the problem, but there might be multiple more problems showing up (e.g. fetch errors, file structure errors, component/App level errors).

Upvotes: 2

Related Questions