Search code examples
vue.jsvuexvuejs3

Vue3: Get updated state from Vuex into component


When I update the user state in Vuex I want it to also update in the frontend instantly without a page reload. I've found some related questions, but they didn't work for me.

One thing I'm exporting the store as a function.

This is what I have right now:

<div v-if="user">
    test
</div>

<script>

import store from "../store";

export default {
    data() {
        return {
            user: store().getters.getUser
        }
    },

    methods: {
        // Updates the store
        login : async function() {
            await this.form.post('/api/auth/login')
                .then(response => {
                    store().dispatch('login', response.data)
                })
        }
    }

}

</script>

And then my vuex store would be like this:

import Vuex from 'vuex'
import Cookie from 'js-cookie';

const createStore = () => {
    return new Vuex.Store({
        state: {
            user: Cookie.get('jwt') ?? ''
        },

        getters: {
            getUser() {
                return state.user
            }
        },

        mutations: {
            SET_USER(state, user) {
                state.user = user
            }
        },

        actions: {
            login({commit}, user) {
                commit('SET_USER', user._id)
                Cookie.set('jwt', user._id, { expires: 7});
            }
        },
    })
}

export default createStore;

I've got the vue configuration correct and it's totally working except for the instantly updating frontend, it needs a page reload before the content gets updated.

I would appreciate any help


Solution

  • Changes to the store are not in scope of data properties. Change user from being a data property in your component to a computed property as recommended by the Vuex docs

    computed: {
      user () {
        return store().getters.getUser
      }
    }