RyanP13
RyanP13

Reputation: 7743

Load async data into the vuex store when Nuxt app loads

I am trialling a project in Nuxt. Liking it so far except I am a little confused as to how to load data from an external async service so that it is available in Vuex from the very first route.

I have tried adding middleware on the default layout to dispatch the store action but I do not see the service being called straight away. Only when I navigate deeper into the routes do I see the action dispatched.

I did something similar in a standard Vue project and added the created method to the App.vue. Is there a similar way in Nuxt?

Upvotes: 0

Views: 2062

Answers (1)

Miloš Pantelinac
Miloš Pantelinac

Reputation: 96

What you need is called a fetch.

The fetch method, if set, is called every time before loading the component (only for page components). It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.

Warning: You don't have access of the component instance through this inside fetch because it is called before initiating the component.

async fetch({ store }) {
  await store.dispatch('your-action')
}

If you need parameter:

async fetch({ store, params }) {
  await store.dispatch('your-action', params.id)
}

I gave an example of id. The name of the parameter depends on the name of your page.

_id => params.id
_slug => parmas.slug
...

Upvotes: 3

Related Questions