Array in vue storage not available in component (in time)
P粉914731066
P粉914731066 2023-09-13 18:14:56
0
1
703

In my application I have a set of game cards stored in the vuex store.

The player fills in a game pin and the code checks it and gets the game cards for that pin and stores them in storage and opens the memory component:

checkPinExists(){
    
        //this.$store.dispatch('retrieveGameByPin', this.enteredPin)
        this.retrieveGameByPin(this.enteredPin)
        .then(res =>  {
            this.fetchGameCards(this.currentGame.id);  // als spel bestaat de bijbehorende kaarten in de store opslaan
            this.currentGameError = false;    // dus als we hier zijn is er geen gameerror...
            this.checked= true;
        if (this.currentGame.game_status === 'actief'){
            this.$router.push("memory");
        }
        })  
        .catch(err => {
            this.currentGameError = true;
            console.error(err);
        });
      
            
    }

fetchGameCrds is a vuex operation:

export const fetchGameCards = ({commit}, game_id) => {
    return new Promise((resolve, reject) => {     
        let status = '';
        let data ={};
       console.log("fetching gameCards  ");
        fetch(`api/cardsByGame/${game_id}`)
        .then(async res => {
            status = res.status;
            if(status === 200) {
                data = await res.json(); 
            }
            else {
                data =null;
            } 
        })
        .then(res=>{
            if ( status === 200) {
                commit('SET_GAME_CARDS', data);
                resolve('GameKaarten gevonden');
            }
            else {
                reject('Geen gamekaartenkaart beschikbaar');
            }
        });
    });
}

In the memory component, the cards are retrieved and the game begins. Unfortunately I couldn't get the game card from the store in time.

In the developer pane of the browser, I do see that the card is in the store.

Memoryscript starts with some debug messages:

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

export default {
   mounted() {
        
    console.log("at mounted show GameCards:"),
    console.log(this.gameCards);

    this.createDeck(),
    this.createShowCards()
           
    },

    computed: {
        ...mapState([
        'currentSpeler' ,'currentSpelerCard', 'currentGame', 'gameCards'
        ]),

The output in the console is a bit like:

at mounted show GameCards:

[Handler]]: Array(0)
length: 0

Can anyone see how I can solve this problem?

I don't want to get the cards in the component itself because I also want to use the game cards in other components instead of getting them from the backend every time.

P粉914731066
P粉914731066

reply all(1)
P粉652495194

If the gameCards array is not populated when the component is mounted, you can use Observers to run your function when gameCards is actually ready for use

watch: {
    // whenever gameCards is assigned a new value, this function will run
    gameCards(newValue, oldValue) {
      // only do this after first assignment (when gameCards is initially empty)
      if(oldValue.length === 0) {
        this.createDeck()
        this.createShowCards()
      }
    }
  },

The watcher will always run when a new array value is allocated, but as my code example shows, you can use logic based on the old and new array values ​​passed in to control whether the watcher actually does anything. p>

Although by default observers only run on a complete reallocation of the observed array, you can use deep observers if you need to.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template