Init pinia state
Asked Answered
C

1

12

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
        }
    }
})
Corydon answered 16/8, 2021 at 13:41 Comment(2)
Just had the same problem last week, and solved it by doing pretty much what you did. I check if store is empty (I set all values to 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
In addition to @Unspent comment above, you should persist the data. This way if the user refreshes in page 2, the data would stored on the user's machine and won't be empty.Elviselvish
B
0

in the first page save the list of countries to local storage then when the user navigates to the second page you get the data form the store and in the store you will try to check if the data is avalable in local storage and get it this will reduce the api calls and if you don't need the data anymore let's say when you exit the second page on unmounted for example clear the localstorage

Bentz answered 30/5 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.