Search code examples
nuxt3pinia

Subscribing all pages/components to multiple stores in nuxt 3 using pinia


I've just started transioning from nuxt2/vuex to nuxt3/pinia and I am trying to figure things out.

I created a store to handle my authentication apis and I noticed that when I am on page /login I can see my store / states in pinia inside vue devtools but when I go to /index or any other page the states are gone in pinia inside vue devtools

So I figured that there might be a missing configuration or I am doing something wrong

I tried many things and finally I managed to subscribe into the store on the entire app from my understanding doing the following

My app.vue

<template>
  <NuxtLoadingIndicator />
  <NuxtLayout>
    <v-app>
      <NuxtPage />
    </v-app>
  </NuxtLayout>
</template>

<script>
import { useAuthStore } from "@/stores/auth";
export default {
  setup() {
    const authStore = useAuthStore();
  },
};
</script>

My auth store

// store/auth.js
import { defineStore } from "pinia";

export const useAuthStore = defineStore("auth", {
  state: () => ({
 successSnackbar: false,
    successMessage: "",
 user: {},
}),
 persist: {
    storage: persistedState.localStorage,
  },|

actions:{ //..},
getters:{ //..},

});

I want to know if this is best practice or even the correct way of doing things in nuxt3/pinia

Now I can see the states on all pages just fine


Solution

  • I would do it like this without pinia, first off, in your nuxt.config
    file do this : 
    
    runtimeConfig: 
       { 
         public : { 
           AUTH_SUCCESS_STATUS: false, 
           AUTH_MSG:'' 
       } 
    } 
    
    then in your vue files:
    
        <script setup>
    const { $config } = useNuxtApp();
    
    if (process.client) {
      const successStatus = window.localStorage.getItem(
        $config.public.AUTH_SUCCESS_STATUS
      );
    }
    </script>
    
    this way , the data is persisted on refresh, it can be used globally in all pages and component just by using `window.localStorage.getItem($config.public.AUTH_SUCCESS_STATUS)` and to manipulate it you can use the
    other options of localStorage.
    

    another way is to use cookie setup and managing that cookie by useCookie composable