Home > database >  react - remove element from list unintentionally clears object properties
react - remove element from list unintentionally clears object properties

Time:09-05

const [quiz, setQuiz] = useState({
    title: "",
    number: 6,
    questions: [
      {
        question: "q1",
        number: 3,
        answers: [
          {
            content: "a1",
            number: 1.5
          },
          {
            content: "a2",
            number: 1.5
          }
        ]
      }
    ]
  });

  const [selectedQuestion, setSelectedQuestion] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState(0);

  useEffect(() => {
    setSelectedQuestion(0);
    setSelectedAnswer(0);
  }, []);

This console log is the desired output:

console.log(quiz.questions[selectedQuestion].answers.filter((element, index) => index !== selectedAnswer))

I am trying to achieve it with this setState:

        setQuiz((prev) => ({
          ...prev, questions: prev.questions.map((question, x) => {
            if (x === selectedQuestion) { 
                console.log(question.answers.filter((element, y) => y !== selectedAnswer ))
              return question.answers.filter((element, y) => y !== selectedAnswer )
            }
            return question;
        })
      }));

All the data inside parent question will be deleted instead in addition to the selected answer.

This is the data before deleting:

enter image description here

This is the data after deleting:

enter image description here

CodePudding user response:

The problematic code is in this block:

if (x === selectedQuestion) { 
    console.log(question.answers.filter((element, y) => y !== selectedAnswer ))
    return question.answers.filter((element, y) => y !== selectedAnswer )
}

If the mapping function encounters the selected question, it only maps the question to the filtered answers, without the remaining question data. I suggest you replace the return statement as follows:

if (x === selectedQuestion) {
  const answers = question.answers.filter((element, y) => y !== selectedAnswer);
  console.log(answers);
  return { ...question, answers };
}
  • Related