Search code examples
vuexvuejs3

State management in vue3 with vuex4 fails - Code shared in codesandbox


Dear friends of the modern lightweight web, I hope you can help a noobie regarding vue3 and Vuex 4.

I share timetable details (array of objects/dictionary) between multiple child components, which then can be displayed (e.g. Top 5 work) or edited (e.g. add new work details) in a way that these changes get reflected in all the other components. For this, I tried to use Vuex 4.

I am not able to access the state in a component. For debugging reasons, I even added a dummy entry during the creation of the state.

https://codesandbox.io/s/dazzling-brahmagupta-5sn1t?file=/src/main.js


Solution

  • Your demo uses Vuex 3 (perhaps that was a mistake only in the demo). Be sure to install Vuex 4, which provides the createStore() method:

    npm i -S vuex@4
    

    Also, the result of createStore() should be passed to app.use(), which is an instance method of the app from createApp() (not the App.vue component):

    import { createApp } from 'vue'
    import { createStore } from 'vuex'
    import App from './App.vue'
    
    const store = createStore(/*...*/)
    
    // App.use(store) ❌ don't do this
    
    createApp(App)
      .use(store) ✅
      .mount('#app')
    

    demo