Skip to content
Advertisement

React State seems to be overwritten / setState seems not to work

I am learning React and I think I am missing something fundamental with updating the state / rendering components.

const allFalse = new Array(data.length)
const allTrue = new Array(data.length)
    
allFalse.fill(false)
allTrue.fill(true)

const [memoryStatus, setMemoryStatus] = useState(allFalse)
const [baseValue, setBaseValue] = useState(false)

The memory game has 5 cards at this point (just learning here) and depending on the memoryStatus it is determined if one side or other side is shown (true / false).

When clicked on a card I obviously want to change the value of that card in the array. I am doing that with this function:

    const handleChange = (position) => {
        const newMemoryStatus = memoryStatus.map((item, index) => 
                { 
                   if(index === position) {
                       return !item
                   }
                   else return item
                }
        )
        // i really dont understand why this does not change the state
        setMemoryStatus[newMemoryStatus]
}

The render part is:

 <div className={styles.container}>
            {data.map((item, index) => {
                return (
                    <div
                        key={index}
                        onClick={() => {handleChange(index)}}
                        className={styles.card}
                    >
                        {!memoryStatus[index] && <Image
                            src={item.img}
                            width="100px"
                            height="100px"
                        />}
                        <span>
                            <center>
                                {memoryStatus[index] ? item.latinName : ''}
                            </center>
                        </span>

                    </div>

                )})
            }
        </div>

Just in case it matters my data looks like this:

const data = [
{
    name: 'Staande geranium',
    latinName: 'Pelargonium zonate',
    img: '/../public/1.png'
},
{
    name: 'Groot Afrikaantje',
    latinName: 'Tagetes Erecta',
    img: '/../public/2.png'
},
{
    name: 'Vuursalie',
    latinName: 'Salvia splendens',
    img: '/../public/3.png'
},
{
    name: 'Kattenstaart',
    latinName: 'Amaranthus caudatus',
    img: '/../public/4.png'
},
{
    name: 'Waterbegonia',
    latinName: 'Begonia semperflorens',
    img: '/../public/5.png'
}]

What am I doing wrong ??

Advertisement

Answer

setMemoryStatus is a function, thus you should be using parentheses () instead of brackets [] when calling it. The line to call it should be:

setMemoryStatus(newMemoryStatus);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement