I initialized a new constant like that :
const [data, setData] = useState([
{
id: "a1",
score: "",
name: "MyA1"
},
{
id: "a2",
score: "",
name: "MyA2"
}
]);
I want to change the score with setData. But I don’t know how to access to data[0].score and data[1].score with setData
I tried to do :
const updateList = (data) => {
setData(previousState => {
return { ...previousState, score:'Good' }
});
}
but it is not working because with this code I can’t access to data[0]. I tried also :
const updateList = (data) => {
setData(previousState => {
return { ...previousState, previousStat[0].score:'Good' }
});
}
but it is not working too.
Do you know how to do that ? Thank you !!
2
Answers
You can do this by retrieve the current state of data using setState.
Try this.
Your first issue is that your useState hook is managing an array of objects. The first code snippet you provided is trying to spread the array like it’s an object, which isn’t quite right. The second snippet contains a syntax error (you’re trying to use object property assignment inside the spread operator).
try this :