NuxtJS + Vuex — datas in the store

Viewed 5450

Using NuxtJS (a VueJS framework), I’m trying to get a bunch of datas from a REST API in a layout template (which can’t use the classic fech() or asyncData() methods).

So I'm using vuex and the nuxtServerInit() action. This way, I should be able to gather all the datas directly during the load of the app, regardless of the current page.

But I can’t get it to work.

Here’s my map.js file for the store:

import axios from 'axios'

const api = 'http://rest.api.localhost/spots'
 
export const state = () => ({
 markers: null
})

export const mutations = {
 init (state) {
  axios.get(api)
   .then((res) => {
    state.markers = res.data
   })
 }
}

export const actions = {
 init ({ commit }) {
  commit('init')
 }
}

And the index.js (that can fire the nuxtServerInit()):

export const state = () => {}

export const mutations = {}

export const actions = {
 nuxtServerInit ({ commit }) {
  // ??
  console.log('test')
 }
}

But I can’t get it to work. The doc says:

If you are using the Modules mode of the Vuex store, only the primary module (in store/index.js) will receive this action. You'll need to chain your module actions from there.

But I don’t know how I shall do this. How do I call an action defined in another module/file?

I tried to copy various example, but never got them to work ; this is the best I could come up with.

What did I missed? If needed, here’s the repo and the store folder

Thanks!

1 Answers
Related