Here my React state:
const [questionList, setQuestionList] = useState([
{
_type: "radio",
answer: "",
point: "",
question: "",
options: ["A", "B"],
},
]);
When the array has many objects, to update an object I code like this and it works fine now:
<textarea
rows="2"
value={questionList[number].question}
onChange={(e) => {
let a = questionList[number];
a.question = e.target.value;
setQuestionList([
...questionList.slice(0, number),
a,
...questionList.slice(number + 1),
]);
}}
></textarea>
Is there a way to make the variable a declaration inside the setState, I mean these 2 rows:
let a = questionList[number];
a.question = e.target.value;
Edit: Sorry I forgot. number value is the position of the object in the array.
>Solution :
You can copy the questions first, mutate the array and set it as the new state without slicing.
<textarea
rows="2"
value={questionList[number].question}
onChange={(e) => {
const copy = [...questionList];
copy[number].question = e.target.value;
setQuestionList(copy);
}}
/>