3

Have a little problem with my useState Hook. I want to change only "answer".

const [questions, setQuestions] = useState({
    question1: { answer: "1", isCorrect: false },
    question2: { answer: "1", isCorrect: false },
    question3: { answer: "1", isCorrect: false },
    question4: { answer: "1", isCorrect: false }
  });
const onChange = e => {
    setQuestions({
      ...questions,
      [e.target.name]: { answer: e.target.value }
    });
  };

This function works, but isCorrect disappear.

I know I can use [e.target.name]: { answer: e.target.value, isCorrect: false} but I want a previous state. ...isCorrect doesn't work. It shoud be so easy but I cant find solucion. I wish someone can help me with that.

Dupocas
  • 20,285
  • 6
  • 38
  • 56

2 Answers2

3

spread the original object and overwrite answer

   const onChange = e => {
    setQuestions({
      ...questions,
      [e.target.name]: { ...questions[e.target.name], answer: e.target.value }
    });
  };
Dupocas
  • 20,285
  • 6
  • 38
  • 56
3

You need to use spread syntax for the nested values too and override the answer key

const onChange = e => {
    setQuestions({
      ...questions,
      [e.target.name]: { ...questions[e.target.name], answer: e.target.value }
    });
  };
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400