After creating a store action to fetch an API, I encountered an error when trying to dispatch it from the component's created lifecycle hook. The error message displayed was 'Cannot read property 'dispatch' of undefined'. Despite researching similar questions, none of the suggested solutions resolved this issue.
I attempted to dispatch the action in a normal method as well, only to encounter the same error.
In the store.js file:
import Vue from "vue";
import Vuex from "Vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
categories: []
},
mutations: {
SET_CATEGORIES(state, categories) {
state.categories = categories;
}
},
actions: {
getCategories({ commit }) {
return fetch("https://api.chucknorris.io/jokes/categories")
.then(response => {
return response.json();
})
.then(jsonObj => {
commit("SET_CATEGORIES", jsonObj);
})
.catch(error => {
console.log(error);
});
}
}
});
Below is the component where the dispatch is being attempted -
<script>
export default {
data() {
return {
joke: "",
categories: [],
selectedCat: ""
};
},
computed: {
disabled() {
if (this.joke) {
return false;
} else {
return true;
}
}
},
methods: {
addToFavs: function() {
this.$emit("pushJoke", this.joke);
this.fetchJoke();
}
},
created() {
this.$store.dispatch('getCategories');
}
};
</script>
Could you please lend your expertise in identifying what might be causing this issue?