1
votes

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?

1
Why did you put nuxtServerInit in actions? - Muhammad
nuxtServerInit is a hook that can be used to initialize something when server is initialized, you can populate your store from there or you can also use fetch or asyncData hooks in your page level components to do it, calling a store action from above hooks will populate your store on server. - Muhammad

1 Answers

2
votes

I believe that the nuxtServerInit action is properly called. My bet is that message has always value of undefined, because Axios.get("http://localhost:5000/api/home") returns promise which does not have attribute data. You have to first await the result and then get it's data.

// note extra parentheses
const message = await (Axios.get("http://localhost:5000/api/home")).data;

Additionally, you may want to wrap the axios call in try-catch, otherwise you'll get the default Nuxt error page with stack trace should the call fail.

  async nuxtServerInit ({ commit }: any) {
    try {
      const message = (await Axios.get('http://localhost:5000/api/home')).data;
      console.log(message);
      commit('setMessage', message); // put name of mutation as parameter + payload
    } catch (error) {
      // you could redirect to custom error page for instance
      console.error(error);
    }
  }