'React state doesn't update with useState
I'm trying to update react state as described below. I do understand that I don't make a correct copy of the previous state, but I can't really make that to work.
setMainData(
data.map((item, id) => {
return {
...mainData[id],
[`data_${id}`]: [...mainData[id][`data_${id}`], 1],
};
})
);
Basically, what I'm trying to do here is to have a structure like this:
[{ data_0: [1]}, {data_1: [1]}]
and after interval tick, add to array without overriding the previous state like this
[{ data_0: [1, 2]}, {data_1: [1,2]}]
Solution 1:[1]
You should like this
const arr = data.map((item, id) => {
return {
...mainData[id],
[`data_${id}`]: [...mainData[id][`data_${id}`], 1],
};
})
setMainData(arr)
maybe its work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BIRKAN |
