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?
>Solution :
To update a specific element in the option array in your state, you can create a new array.
Here is one of the ways.
const handleOption = (e) => {
const { id, value } = e.target;
setRes((prev) => {
const updatedOption = [...prev.option]; // Create a copy of the option array
updatedOption[id] = value; // Update the value at the specified index
return { ...prev, option: updatedOption }; // Return the updated state
});
};