Search code examples
vue.jsvuejs3vitepinia

Vue3 Pinia Store cannot access 'store" before initializsation


I have a UserStore which contains some information about the current user. This store also is responsible for loggin in and out.

In order to make the getters available I map the getters to my computed attribute within my Vue component.

Unfortunately I get an error saying that it cannot access useUserStore before initilization.

This is my component:

<template>
  //...
</template>

<script>
import {mapState} from "pinia"
import {useUserStore} from "../../stores/UserStore.js";
import LoginForm from "../../components/forms/LoginForm.vue";

export default {
  name: "Login",
  components: {LoginForm},
  computed: {
    ...mapState(useUserStore, ["user", "isAuthenticated"]) //commenting this out makes it work
  }
}
</script>

This is my store:

import { defineStore } from 'pinia'
import {gameApi} from "../plugins/gameApi.js"
import {router} from "../router.js";

export const useUserStore = defineStore("UserStore", {
    persist: true,
    state: () => ({
            authenticated: false,
            _user: null
    }),

    getters: {
        user: (state) => state._user,
        isAuthenticated: (state) => state.authenticated
    },

    actions: {
        async checkLoginState() {
            // ...
        },
        async loginUser(fields) {
            // ...
        },
        async logutUser() {
            // ...
        }
    }
})

And my main.js

import {createApp} from 'vue'
import App from './App.vue'
import gameApi from './plugins/gameApi'
import {router} from './router.js'
import store from "./stores/index.js";

createApp(App)
    .use(store)
    .use(router)
    .use(gameApi)
    .mount('#app')

And finally my store configuration:

import {createPinia} from "pinia"
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import {useUserStore} from "./UserStore.js";

const piniaStore = createPinia()
piniaStore.use(piniaPluginPersistedstate)

export default {
    install: (app, options) => {
        app.use(piniaStore)

        const userStore = useUserStore()
        const gameStore = useGameStore()
    }
}

Solution

  • I wasn't able to initialize the store using the "old" way comparable with Vuex. Instead I had to make use of the setup() function Pinia Docu:

    <script>
    import {useUserStore} from "../../stores/UserStore.js";
    
    export default {
      name: "RegisterForm",
    
      setup() {
        // initialize the store
        const userStore = useUserStore()
        return {userStore}
      },
    
      data() {
        return {
          // ...
        }
      },
    
      methods: {
        checkLoginState() {
          this.userStore.checkLoginState()
        }
      }
    }
    </script>