bdoubleu
bdoubleu

Reputation: 6127

Vuex state not updating from local storage

I'm having some problems getting the Vuex state to update from local storage when visiting a route directly from the address bar in an incognito window.

When visiting the route /shop/:key? directly (for example clicking a link from an email) the mounted action getDetail is executed and local storage is updated but the state is not reevaluated - it still says undefined as if the key doesn't exist.

Is there a way to get the state to be reevaluate or does it have to be updated in the setDetail mutation?

const state = {
    key: localStorage.getItem('key'),
    details: null
}

const actions = {
    async getDetail({ commit }, key) {
        const details = await Service.detail(key)
        commit('setDetail', details)
    }
}

const mutations = {
    setDetail(state, details) {
        state.details = details
    }
}

const Service = {
    detail: async function(key) {
        const url = `/store/${key}/`
        const response = await ApiService.get(url)
        localStorage.setItem('key', key)
        return response.data
    }
}

Upvotes: 2

Views: 2682

Answers (2)

Joey Sanchez
Joey Sanchez

Reputation: 11

localStorage might be returning a string instead of a boolean which if not properly handled could lead to vuex not updating state accordingly.

Upvotes: 0

Radu Diță
Radu Diță

Reputation: 14211

The state will be re-evaluated if a mutation (or action) occurs. You could change the state directly but this is advised against as it breaks reactivity.

LocalStorage is not reactive and as such you need to update the state using a mutation or an action.

Upvotes: 1

Related Questions