skip to Main Content

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


  1. 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
      });
    };
    
    Login or Signup to reply.
  2. Create a copy of your array using the previous value, update your desired index and return a new object to your state.

    const handleOption = e => {
      setRes(prev => {
        const newOptions = [...prev.options];
        newOptions[e.target.id] = e.target.value;
    
        return {
          ...prev,
          options: newOptions
        };
      });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search