Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shorter way to update state of array of object?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
  }}
/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading