0

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

1 Answer 1

2

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
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This didn't work for me even after I've made the store accessable through this.$store. It's only updating after a page refresh. FYI: I'm building a SPA which has no page reloads maybe that's preventing from updating?
After also changing the store().dispatch() function to this.$store.dispatch() it actually worked. I'm just wondering why store().dispatch() doesn't work, but this.$store.dispatch() does work. Anyways I'll mark your answer. Thanks for your help and reply!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.