Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

75
Vistas
How to update a single object inside the array with useReduce on state change

I have a checkbox component and when a value is selected for a checkbox, I want to update my state with true and false values. In total I have 5 different states.I cannot update the single object from my state. Can someone help?

With the current implementation quizState becomes undefined after I set the value

My reducer looks like this:

quizState: [
    {id:0, question_id: '', answer: [] },
    {id:1, question_id: '', answer: [] },
    {id:2, question_id: '', answer: [] },
    {id:3, question_id: '', answer: [] },
    {id:4, question_id: '', answer: [] },
],

export const appReducer = (state = appState, action) => {
const { type, payload } = action;

switch (type) {
    case SET_QUIZ_STATE:
        return state.quizState.map((quiz) => quiz.id === payload.id ? ({...quiz, payload}) : quiz)

    default:
        return state;
}};

And I have a hook:

const setQuizState = useCallback(
    (quizState) => dispatch({ type: SET_QUIZ_STATE, payload: quizState }),
    [dispatch]
);

In the component, on change event:

  setQuizState({ id: 0, question_id: question.question_id, answers: [true, false] });
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are returning only the subfield quizState where the whole state is needed. Change your reducer like below:

export const appReducer = (state = appState, action) => {
  const { type, payload } = action;

  switch (type) {
    case SET_QUIZ_STATE:
      return {
        ...state,
        quizState: state.quizState.map(prevState => {
          if(prevState.id !== payload.id) return prevState;
          return {
            ...prevState,
            ...payload
          }
        })
      };
    default:
      return state;
  }
};

And this answer assumes that payload object is compatible to be an element in the quizState array. I think you have a typo in your onChange event where you are putting answers, not answer for your payload.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda