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

Accessing array with JSON in React

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

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

  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
  });
};
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