vuex: createStore with key get error after vite hot updated

Version

4.0.1

Steps to reproduce

main.js

// main.ts
import { createApp } from 'vue'
import { store, key } from './store'

const app = createApp({ ... })

// 传入 injection key
app.use(store, key)

app.mount('#app')

store.js

import { InjectionKey } from 'vue'
import { createStore, useStore as baseUserStore, Store } from 'vuex';

// 为 store state 声明类型
export interface State {
  count: number
}

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol('admin-store')

const store = createStore<State>({
  state: {
    count: 0
  }
})

export default store;

export function useStore<T = State>(): any {
    return baseUserStore<T>(key);
}

index.vue

import { useStore } from './store'

export default {
  setup () {
    const store = useStore() //  undefined

  }
}

What is expected?

when I change index.vue and save, vite finish hot update can correct to get useStore() in setup function

What is actually happening?

when I change index.vue and save, vite finish hot update useStore() return undefined, and warnning injection “Symbol(admin-store)” not found


but I remove key,it‘s work fine.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 18 (3 by maintainers)

Most upvoted comments

export const key: InjectionKey<Store<State>> = Symbol('admin-store')

can you fix it by taking Symbol to Symbol.for ?

临时解决办法

// 定义 injection key
export const storeKey: InjectionKey<Store<State>> = '__app_store_key__' as any

I have the same problem.

in *.vue use import { useStore } form 'xxx/store.js' // not from 'vuex'

eg:

// in a vue component
import { useStore } from './store'

export default {
  setup () {
    const store = useStore()

    store.state.count // typed as number
  }
}

I had the same problem.

I had the same problem.