0

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?

1 Answer 1

3

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
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.