Reputation: 3857
According to the Nuxt documentation these methods are used to pre-fill store before page is served.
In what cases should I use fetch
and in what cases - nuxtServerInit
?
Upvotes: 4
Views: 2552
Reputation: 493
Use nuxtServerInit
if you need to fill the store with specific data from the very beginning, no matter which page was accessed first.
Use fetch/asyncData
when a specific page is accessed and you need to fill the vuex store (or the page data
object) for this page specifically.
Upvotes: 4
Reputation: 145
nuxtServerInit: it is used to fetch some data you work with a lot (such as userInfo in the session), only once, then you can use it in all the components. So, you don't have to constantly reach out to the server. Moreover, it is an action in the store provided by Vuex, so it'll dispatch automatically by Vuex.
fetch/asyncData: they are executed before rendering the page both server-side (when you refresh the page) and client-side (when you click around and route to the page). However, fetch used only to fill the store (you can get the data from the store in computed), and asynchData used to set the component data (you can fill the store in created hook).
References: https://nuxtjs.org/guide/vuex-store#the-nuxtserverinit-action and https://nuxtjs.org/api/pages-fetch
Upvotes: 1
Reputation: 10517
I think of nuxtServerInit
as the place to go if I need to make requests that prefetch options that are used in all the App, languages, configaration values, input options, etc...
fetch
&asyncData
instead fire both on the client and server once that pages gets rendered.
That means that fetch
& asyncData
will fire every time the component is matched by the router and nuxtServerInit
only once, at the beginning, on the server, and never again.
Upvotes: 7