Siwyus
Siwyus

Reputation: 35

Changing part of state

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.

Upvotes: 3

Views: 55

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281626

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

Upvotes: 3

Dupocas
Dupocas

Reputation: 21297

spread the original object and overwrite answer

   const onChange = e => {
    setQuestions({
      ...questions,
      [e.target.name]: { ...questions[e.target.name], answer: e.target.value }
    });
  };

Upvotes: 3

Related Questions