Search code examples
vue.jsvuejs3vuex

How can I make Component visible using vuex stored value, using mapstate and funtion in parent component


In a Game component i have to components: Memory and NamesByPictures. The visibility is set by v-if dependency of Vuex store parameters.

When a player enters a pint, it is checked, and when it is correct the memoryVisible parameter is ste to true. Yet it remains false in the store when I check it in the Vue-devtools.

Here is my script:

<template>
<div class="custom-container">

    <Memory v-if="memoryVisible"></Memory> 
    <NamesByPictures v-if="namesByPicturesVisible" ></NamesByPictures>

</div>
</template>

<script>
    import { mapState , mapActions} from 'vuex';

    export default{
    mounted(){    
    },
    computed: {
        ...mapState([ 'currentGame', 'memoryVisible', 'namesByPicturesVisible']),        
    },
    data(){
        return{
            enteredPin: 9999,
            pinCorrect:false,
            gameName: '',
            currentGameError:false,
            checked:false,
            errorMessage:'',
            successMessage:'',
        }
    },
    methods: {

        ...mapActions(['fetchGameCards']),


            checkPinExists(){
            this.$store.dispatch('retrieveGameByPin', this.enteredPin)
            .then(res =>  {
                this.currentGameError = false;    // dus als we hier zijn is er geen gameerror...
                this.memoryVisible=true;   
                this.checked= true;                  
            })  
            .catch(err => {
                this.currentGameError = true;
                console.error(err);
            })
                
        }
    }
}
</script>

and the state.js:

export default{
    cards:[],
    games:[],
    token:localStorage.getItem('access_token') || null,
    currentGame:{},
    currentSpeler:{},
    currentSpelerCard:{},
    gameCards:[],
    memoryVisible:false,
    namesByPicturesVisible:false

}

Can anyone explain this behaviour?


Solution

  • Actually, it seems you're updating memoryVisible only in local component state. This will not update the store's state.

    To update memoryVisible in the store state, you need to create a mutation in your store :

    mutations: {
      setMemoryVisible(state, visible) {
       state.memoryVisible = visible;
      }
    }
    

    After that, you can dispatch the mutation in your function checkPinExists():

    this.$store.commit('setMemoryVisible', true);