Sock Monkey
Sock Monkey

Reputation: 333

Vue component not updating on state change

<div v-for="(photon, key) in $store.state.notConnected" v-bind:key="key">
    <div v-if="!photon.connected">
        <p>Photon is not Connected</p>
    </div>
    <div v-if="photon.connected">
        <p>Photon is Connected</p>
        <b-btn v-on:click="showNewSetup(photon)>Setup</b-btn>
    </div>
    <div v-if="photon.showSetup">Setup Page</div>
</div>    

Store.js

export const store = new Vuex.store({
 state:{
   notConnected:{}
 },
 mutations:{
 setDevices(state,value){
 value.data.forEach(ele =>{
 state.notConnected[ele.id]={}
 state.notConnected[ele.id].showSetup=false
 state.notConnected[ele.id].connected=ele.connected
 }
 },
 SHOWNEWSETUP(state,value){
  state.notConnected[value.id].showSetup=true
}}
actions:{
async getDevices(context){
let devices = await axios.get('http:10.10.10.1:3000/api')
context.commit('setDevices',devices)
}
}
})

I'm mutating the state in my vuex store but the v-if doesn't reflect the updated state. When I open up vue dev tools I see the mutation happen and can see that the state has changed, but the setup page div isn't updating.

Note: If i go to a diffrent route and go back to the page the component updates

Upvotes: 0

Views: 2993

Answers (2)

Steve Aksamit
Steve Aksamit

Reputation: 11

Try using a computed property in your component instead of pointing to state directly:

<template>
    <div v-for="(photon, key) in photons v-bind:key="key">
        <div v-if="!photon.connected">
            <p>Photon is not Connected</p>
    </div>
    <div v-if="photon.connected">
        <p>Photon is Connected</p>
        <b-btn v-on:click="showNewSetup(photon)>Setup</b-btn>
    </div>
        <div v-if="photon.showSetup">Setup Page</div>
    </div>   
</template>

<script>
    computed: {
        photons() {
            return this.$store.state.notConnected
        },
    }
</script>

Upvotes: 1

Thomas
Thomas

Reputation: 2536

Vue has no chance to detect changes in Arrays (except vue3 with proxy support).

That's why you should alter your mutation to:

SHOWNEWSETUP(state,value){
  Vue.set(state.notConnected, value.id, {showSetup=true})
}

That way Vue's reactivity system is informed about the change and everything should work as expected.

Upvotes: 1

Related Questions