Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
React state update not working with setState

Okay so it's simple

I have an array of answers inside an array of questions. the user has the option to select more than one answer.

When an answer is selected, the text should change to selected and unselected if it isn't selected.

These are the steps i've tried to update my state

step 1 using map

setTestInfo((state) => {
    const allStateQuestions = state.info.questions;

    const currentQuestion = allStateQuestions.filter(
      (question) => question.id === questionId
    )[0];

    const allAnswersMap = currentQuestion.answers.map((answer) =>
      answer.id === answerId
        ? (() => {
            answer.is_chosen = !answer.is_chosen;
            return answer;
          })()
        : answer
    );
    currentQuestion.answers = allAnswersMap;

    return {
      ...state,
      info: {
        ...state.info,
        questions: allStateQuestions,
      },
    };
  });

step 2 using find

setTestInfo((state) => {
    const allStateQuestions = state.info.questions;

    const currentQuestion = allStateQuestions.filter(
      (question) => question.id === questionId
    )[0];

    const currentAnswer = currentQuestion.answers.find(
      (answer) => answer.id === parseInt(answerId)
    );
     
    currentAnswer.is_chosen = !currentAnswer.is_chosen;

    // i even went to the extend of reassigning it yet it doesn't work
    currentQuestion.answers.filter((answer) => answer.id === answerId)[0] =
      currentAnswer;

    return {
      ...state,
      info: {
        ...state.info,

        questions: allStateQuestions,
      },
    };
  });

Well after using the sample logics above, none of them seem to work Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Issue

You are mutating the state in both cases. I'll cover the first snippet.

setTestInfo((state) => {
  const allStateQuestions = state.info.questions; // <-- reference to state

  const currentQuestion = allStateQuestions.filter( // <-- reference to state
    (question) => question.id === questionId
  )[0];

  const allAnswersMap = currentQuestion.answers.map((answer) =>
    answer.id === answerId
      ? (() => {
          answer.is_chosen = !answer.is_chosen; // <-- state mutation!!
          return answer;
        })()
      : answer
  );
  currentQuestion.answers = allAnswersMap; // <-- state mutation!!

  return {
    ...state,
    info: {
      ...state.info,
      questions: allStateQuestions, // <-- saved reference back into state
    },
  };
});

The currentQuestion.answers object of the state.info.questions state was mutated and the state.info.questions array reference never changed so React isn't "seeing" this as an update and isn't triggering a rerender.

Solution

Apply the immutable update pattern. You must shallow copy all updates into new array and object references.

setTestInfo((state) => {
  return {
    ...state,
    info: {
      ...state.info,
      // new questions array
      questions: state.info.questions.map(question => question.id === questionId
        ? { // new question object
          ...question,
          // new answers array
          answers: question.answers.map(answer => answer.id === answerId
            ? { // new answer object
              ...answer,
              is_chosen: !answer.is_chosen,
            }
            : answer
          ),
        }
        : question
      ),
    },
  };
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda