Static GitHub Issues

[965] Best practice: Fetching async intial state for Vuex store being used in SSR?

prev: Generate a static 404 page
next: nuxtServerInit - how to handle errors?

I want to:

  • fetch async data from a rest api
  • use the response data as state for initialising the Vuex store in Nuxt
  • and use that data already server side for rendering

I know I can use the fetch method on a page to populate the store. But the question having in mind is: If having a few different pages, which all depend on that state... can I already load the state as initial state without having to load it on each page separately then?

I tried this:

const setupStore = function () {
  return axios.get('http://localhost:3030/users')
    .then((response) => {
      const storeObject = {
        state: {
          users: response.data.data
        }
      }
      const store = new Vuex.Store(storeObject)
      return store
    })
}
export default setupStore()

Unfortunately this doesn't work as, I guess due to its async nature, the computed map state function is not able to map the data, even though the data is correctly visible in the Vue developer tools.

So what would be the suggested way to solve this problem?

<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c832">#c832</a>)</em></sub></div>