I am learning React and I think I am missing something fundamental with updating the state / rendering components.
JavaScript
x
9
1
const allFalse = new Array(data.length)
2
const allTrue = new Array(data.length)
3
4
allFalse.fill(false)
5
allTrue.fill(true)
6
7
const [memoryStatus, setMemoryStatus] = useState(allFalse)
8
const [baseValue, setBaseValue] = useState(false)
9
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:
JavaScript
1
13
13
1
const handleChange = (position) => {
2
const newMemoryStatus = memoryStatus.map((item, index) =>
3
{
4
if(index === position) {
5
return !item
6
}
7
else return item
8
}
9
)
10
// i really dont understand why this does not change the state
11
setMemoryStatus[newMemoryStatus]
12
}
13
The render part is:
JavaScript
1
25
25
1
<div className={styles.container}>
2
{data.map((item, index) => {
3
return (
4
<div
5
key={index}
6
onClick={() => {handleChange(index)}}
7
className={styles.card}
8
>
9
{!memoryStatus[index] && <Image
10
src={item.img}
11
width="100px"
12
height="100px"
13
/>}
14
<span>
15
<center>
16
{memoryStatus[index] ? item.latinName : ''}
17
</center>
18
</span>
19
20
</div>
21
22
)})
23
}
24
</div>
25
Just in case it matters my data looks like this:
JavaScript
1
27
27
1
const data = [
2
{
3
name: 'Staande geranium',
4
latinName: 'Pelargonium zonate',
5
img: '/../public/1.png'
6
},
7
{
8
name: 'Groot Afrikaantje',
9
latinName: 'Tagetes Erecta',
10
img: '/../public/2.png'
11
},
12
{
13
name: 'Vuursalie',
14
latinName: 'Salvia splendens',
15
img: '/../public/3.png'
16
},
17
{
18
name: 'Kattenstaart',
19
latinName: 'Amaranthus caudatus',
20
img: '/../public/4.png'
21
},
22
{
23
name: 'Waterbegonia',
24
latinName: 'Begonia semperflorens',
25
img: '/../public/5.png'
26
}]
27
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:
JavaScript
1
2
1
setMemoryStatus(newMemoryStatus);
2