F
F
Floydreme2022-02-26 03:04:16
React
Floydreme, 2022-02-26 03:04:16

Why isn't the state updated?

I'm trying React, I want to write a card memory game. When you click on the card component, the text ( data ) does not appear, but if you try to log, the methods are executed. What could be the problem?

field.js

import React, {useState} from 'react';
import styled from "styled-components";
import Card from "./Card";
import {cardsData, shuffle} from "../common/cards.data";

const FieldGrid = styled.div`
  display: grid;
  grid-gap: 2rem;
  grid-template-columns: repeat(4, 1fr);
`

const Field = () => {
    const [cards, setCards] = useState(() => shuffle(cardsData))
    const [isFlipped, setIsFlipped] = useState(Array<boolean>(cards.length).fill(false))

    const handleFlip = (index: number) => {
        isFlipped[index] = !isFlipped[index]
        setIsFlipped(isFlipped)
    }

    return (
        <FieldGrid>
            {
                cards.map((data, index) => {
                    return <Card key={index}
                                 index={index}
                                 isFlipped={isFlipped[index]}
                                 data={data}
                                 onClick={handleFlip}/>
                })
            }
        </FieldGrid>
    );
};

export default Field;


card.js
import React from 'react';
import styled from 'styled-components'
import CardProps from "../common/interfaces/card.props";

const CardWrapper = styled.div`
  background: #fbfdfd;
  border-radius: 12px;
  width: 10rem;
  height: 10rem;
  padding: 3rem;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 8px 0 rgba(176, 192, 204, 0.2);
  font-size: 3rem;
  text-align: center;
  transition: 150ms background-color ease;
  cursor: pointer;

  &:hover {
    background: #f2f8f8;
  }
`

const Card = (props: CardProps) => {
    const handleClick = () => {
        props.onClick(props.index);
    };

    return (
        <CardWrapper onClick={handleClick}>
            {props.isFlipped ? props.data : ""}
        </CardWrapper>
    );
};

export default Card;


export default interface CardProps {
    data: string;
    isFlipped: boolean;
    index: number;
    onClick: (index: number) => void;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-02-26
@FloydReme

isFlipped[index] = !isFlipped[index]
setIsFlipped(isFlipped)

The value of isFlipped has not changed - the component is not re-rendered. Instead of modifying an existing array, create a new one:
setIsFlipped(isFlipped.map((n, i) => i === index ? !n : n));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question