We use pinia to manage app state. As it's mentioned in title, I'm looking for NuxtServerInit hook analogue for pinia.
A little context: User lands on First page of form; Form calls (f.e.) state.getCountries() to fetch the list of items for one of the select inputs; User selects a country and navigates to Second page, which has to have access to countries list as well; It's ok, when User goes to Second page from the First page; But countries list is empty (obvious) if User refreshes the Second page;
Atm I do like if (state.countries.length === 0) state.getCountries()
But, I believe, it's not a good way
Page 1
<template>
<app-select :items="send.countries" />
</template>
<script>
import { defineComponent } from '@nuxtjs/composition-api'
import { useSend } from '~/store/send'
export default defineComponent({
setup() {
const send = useSend()
send.getCountries()
return { send }
}
}
</script>
Page 2
<template>
<app-select :items="send.countries" />
</template>
<script>
import { defineComponent } from '@nuxtjs/composition-api'
import { useSend } from '~/store/send'
export default defineComponent({
setup() {
const send = useSend()
// if User refreshed Second page, countries is empty list
if (send.countries.length === 0) {
send.getCountries()
}
return { send }
}
}
</script>
store/send.ts
import { defineStore } from 'pinia'
export const useSend = defineStore({
state: () => {
return {
countries: []
}
},
actions: {
getCountries() {
const res = this.$nuxt.$api.countries.get()
this.countries = res.data
}
}
})
null
i.e.countries: null
by default and make simple check i.e.if(countries)
). If store is not empty I get data from store and save me a request, if store is empty (page has been refreshed) I get the data via request again. The only alternatives would be saving data in session or similar... – Unspent