Exploring the world of nuxt.js, I find myself pondering on the most efficient way to fetch data using REST api.
Within my store folder, the structure is as follows:
store
-posts.js
-categories.js
-index.js
Initially, I attempted to set the data using nuxtServerInit
actions in the index.js
:
export const actions = {
async nuxtServerInit({ dispatch }) {
await dispatch('categories/setCategories')
await dispatch('posts/loadPosts','all')
}
}
Unfortunately, this approach did not yield the desired results; although the actions were dispatched on the server, the data was not properly set. As such, I turned to utilizing fetch, albeit encountering the issue of it being triggered every time the page containing posts was loaded. This persisted despite implementing a general layout configuration like so:
<template>
<div>
<Header />
<keep-alive>
<nuxt/>
</keep-alive>
</div>
</template>
Consequently, I resorted to employing a workaround by utilizing fetch within the page component:
async fetch({store}){
if(store.getters['posts/getPosts'].length === 0 && store.getters['categories/getCategories'].length === 0 ){
await store.dispatch('categories/setCategories')
await store.dispatch('posts/loadPosts','all')
}
}
An observation worth noting is that fetch appeared to be ineffective when applied to the root page component (pages/index.vue).
Although my current solution appears to suffice, I am curious if there exists a more optimal method for setting the data?