I've created a Nuxt store for my index page with the intent of initializing the state and fetching some data from an API to mutate the state.
This is the code for my store, including the initial state, mutations and actions.
import Axios from "axios";
//a controller has a store that it interfaces with
// set initial state of the store
const initState = () => ({
message: "init"
})
// make the state usable from other components
export const state = initState
//when you need to change the state
//for mutations you do commits
export const mutations = {
setMessage(state, message) {
state.message = message
}, //can define more functions here
reset(state) {
Object.assign(state, initState())
}
}
//when you have to do API calls (async)
//commit parameter allows us to invoke the mutation functions
//for actions you do dispatch
export const actions = {
async nuxtServerInit({commit}) {
const message = await Axios.get("http://localhost:5000/api/home").data;
console.log(message);
commit("setMessage", message) //put name of mutation as parameter + payload
}
}
In my index.vue file, I import the needed functions from vuex and map the state.
import Logo from '~/components/Logo.vue'
import VuetifyLogo from '~/components/VuetifyLogo.vue'
import Axios from "axios";
import {mapState, mapActions, mapMutations} from 'vuex'
export default {
components: {
Logo,
VuetifyLogo
},
computed: mapState({
message: state => state.message
}),
methods: mapMutations([
"reset",
"setMessage"
])
However when i load up the page (using Vue development tools), my state starts off being undefined. I am able to mutate the state via the "reset" method, but my API is not being called to fetch the data. I don't get any errors in the console, so I'm unsure what is causing this. My API is up and running as well.
How can I make sure that the nuxtServerInit action is called when I load the page?