Search code examples
vue.jsvuex

How to listen for changes in state object loaded from API?


If I set state object like this:

const state: {
    tools: {
        tool1: {
            status: true.
            state: 
        },
        tool2: {
            status: false.
            state: 1
        }
    }
}

on view side everything is changing correctly when I change for example status using mutation.

But If i set tools using API response:

state.tools = response.tools;

where response is 100% identical nothing happens. State object has changes which can also be seen in Vue debuger.

So what I have tried is to add const state: { tools: { tool0: { status: true. state: } } }

and added tool1 and tool1 from ajax (so my object had 3 child element tool0, tool1, tool3). So if I trigger change on tool1 or tool2 (loaded by ajax) nothing happened. But when I trigger change on tool0 (hardcoded before) everything works fine - in this case also settings set on ajax loaded content are applied.

Thanks for any hint!


Solution

  • Did you try to set the state using Vue.set?

    Ref: https://vuex.vuejs.org/en/mutations.html

    From the docs:

    Mutations Follow Vue's Reactivity Rules

    Since a Vuex store's state is made reactive by Vue...

    ...

    When adding new properties to an Object, you should either: Use Vue.set(obj, 'newProp', 123) or ...

    You are adding new props here. You should set it as follows:

    Vue.set(state, tools, response.tools)