btsfreak
btsfreak

Reputation: 11

Vue3/Pinia: Using Pinia store inside a composable throws TypeError within pinia core code

We are running a SPA compiled with vite and Vue3. As soon as we call the useStore() function inside a composable, we encounter a Type Error in the pinia code:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_s')

It happens in the pinia core code

We can use this store without issues anywhere else in our app (SPA). It seems that the composables are run too early and create this error because the pinia instance is not ready yet (similar issue here, albeit with SSG: https://github.com/antfu/vite-ssg/issues/103 )

  1. Create a dummy store import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Ref } from 'vue'

export const useTestStore = defineStore('customer-portal', () => {
  console.log('Defining Teststore...')
  const test: Ref<string> = ref('')
  return {
    test,
  }
})
  1. Create a composable using this store:
import { ref } from 'vue'
import { useTestStore } from '@/vue/store/test'
const store = useTestStore()
  1. Use theat composable in a component (import store and call useTestStore())

Upvotes: 1

Views: 384

Answers (1)

RodP
RodP

Reputation: 393

I know this is an old Q but I had the same issue and this Q helped me to find the answer. According to the pinia help files they state

Pinia stores rely on the pinia instance to share the same store instance across all calls. Most of the time, this works out of the box by just calling your useStore() function. For example, in setup(), you don't need to do anything else. But things are a bit different outside of a component. Behind the scenes, useStore() injects the pinia instance you gave to your app. This means that if the pinia instance cannot be automatically injected, you have to manually provide it to the useStore() function. You can solve this differently depending on the kind of application you are writing.

They provide some good examples of why it works or doesn't work with different import timing. In my case I changed my code so that I only call useStore() inside my Vue components, after pinia is created, and then pass the store as an argument in my function calls.

Upvotes: 0

Related Questions