Different position of the array being called. Memory Game on React

0

I'm making a memory game in React using typescript to learn. In the getCards function, I look for 6 backend cards, put them in an array, duplicate this array, and popup and refresh the screen.

private getCards = async () => {
    const ids: number[] = [1, 2, 3, 4, 5, 6];

    await Promise.all(ids.map(async (id) => {
      const { data } = await Axios.get('http://localhost/mycards/${id}');      
      this.setState(() => ({ cardsDuplicated: [...this.state.cardsDuplicated, data.card] }));

      return data;
    }))

    const { cardsDuplicated } = this.state;
    const otherDuplicate = cardsDuplicated.slice(0);
    const shuffledCards = this.shuffle([...cardsDuplicated, ...otherDuplicate]);

    this.setState(() => ({ canShow: true, cards: [...shuffledCards] }));
  }

This works, the problem is as follows. The moment I click to flip the first card, it flips its duplicate at the same time, as if both were in the same location in the array or in memory. Here is the function to turn the chart below:

private handleTurn = (idx: number) => {
    const { cards } = this.state;    
    const newCards = cards.map((card: ICardInterface, index: number) => {
      if (index === idx) {
        if (card.isTurned) {
          return card
        }

        card.isTurned = !card.isTurned;
        this.setState(() => ({ openedCards: [...this.state.openedCards, card]}));        
      }

      return card;
    });

    this.setState(() => ({ cards: newCards }));
  }

In my conception, I duplicated the array with the spread operator, so each element inside the array should be a new element. The idx parameter received by the function is the position in the array itself, I then make a map where I compare only the two indexes and if both are equal, the letter is turned using the isTurned attribute of the card object, which is the letter itself.

Even by passing the index and performing console.logs they have both different indexes, when clicking a letter both are turned.

I searched the internet and tried to debug in a number of ways but I did not find a solution, I still do not have much knowledge in React or typescript, so I may be forgetting something, or my arrays duplicity logic is not correct.

If anyone can at least point me in one direction would be great, thank you in advance.

    
asked by anonymous 25.12.2018 / 18:53

0 answers