I have a structure as follows:
const [res, setRes] = useState({
question: "",
option: [, , , ,],
answer: 0,
});
I want to update the option array value with corresponding indices.
Example
I should be able to set option[3]:2
const handleOption = (e) => {
setRes((prev) => ({
...prev,
option[e.target.id]:e.target.value,
}));
};
The above snippet gives error at options[e.
How to solve this?
2
Answers
To update a specific element in the option array in your state, you can create a new array.
Here is one of the ways.
Create a copy of your array using the previous value, update your desired index and return a new object to your state.