1
votes

I'm trying to set state vuex on my Nuxt.js App, but it don't work correctly. So here i'm set my state with fetch method:

fetch({app, store, route}) {
    app.$axios.$get(`apps/${route.params.id}`)
      .then(res => {
        store.dispatch('setApp', {
          ...res,
          id: route.params.id
        })
        console.log(app.store.state.app);
      })
  }

Here everything works correcty when i'm logging app.store, data is there, but when i'm trying to log it in:

  created() {
    console.log(this.$store);
  },
  mounted() {
    console.log(this.$store);
  }

Here's my store code:

const store = () => new Vuex.Store({

  state: {
    app: ''
  },
  mutations: {
    'SET_APP' (state, payload) {
      state.app = payload
    }
  },
  actions: {
    setApp (ctx, payload) {
      ctx.commit('SET_APP', payload)
    }
  },
  getters: {

  }
})

i't don't work my state is empty so data is not render on my template ( I hope that somebody gotta help me !

P.S: Also when it's logging on client-side everything works fine, but in SSR not (

1
Could you please add the setApp action to your question ? And also, I don't think that you are logging in the right place, since the created and mounted lifecycle hooks will be executed before your fetch will be done. - Thomas Ferro
@ThomasFerro yes sure, now you can watch on it ) - Albert Jovinskyi
@ThomasFerro i don't know but data is not rendering on my template ( it's empty it works only if it on client-side - Albert Jovinskyi
Thanks, can you try to log your $store in a computed based on the app state ? - Thomas Ferro
@ThomasFerro on the app state, you mean on the fetch method or the index file on store folder ? - Albert Jovinskyi

1 Answers

2
votes

As stated from the docs

To make the fetch method asynchronous, return a Promise, Nuxt.js will wait for the promise to be resolved before rendering the component.

In code example above, axios request is made inside fetch hook, but Nuxt will not wait for it to resolve, as no promise is returned, so it keeps rendering the component, thus running created and mounted hooks, which by the time of invocation do not have filled $store.

In order to make it work, you should return a promise from fetch method.

If no additional code is present in your app, simply adding return statement will solve the issue:

fetch({app, store, route}) {
  return app.$axios.$get(`apps/${route.params.id}`)
    .then(res => {
      store.dispatch('setApp', {
      ...res,
      id: route.params.id
    })
    console.log(app.store.state.app);
  })
}