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

197
Vistas
Is there any way to update a specific array object in reducer in react?

Here I am trying to update my state data with a reducer. I am sending an object through dispatch which is consisted of id, and some data. By this id, I am trying to update a specific object of my state. My state reducer is,

case "UPDATE_USER_SUCCESS":
      return {
        ...state,
        users: state.users.map((user) => {
          if (user.id !== action.payload.id) {
            return user;
          } else {
            return {
              ...user,
              ...action.payload,
            };
          }
        }),
      };

Here is the action,

export const updateUser = (updatedUser) => (dispatch, getState) => {
  dispatch({
    type: "UPDATE_USER_SUCCESS",
    payload: updatedUser,
  });
  console.log(updateUser);
  localStorage.setItem(
    "Users",
    JSON.stringify(getState().addUserReducer.users)
  );
};

ANd my dispatching is from here,

const formHandler = (e) => {
    e.preventDefault();
    dispatch(updateUser(updatedUser));
    console.log(name + email + phone + roles);
  };
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

    return {
              ...user,
              ...action.payload,
            };

what is your goal here? If user was an array, by utilizing this code , you would add action.payload to your array. But user is an object. If you want to pass another object to it, you have to give it a key:

    return {
              ...user,
              whateverkey:action.payload,
            };

and your user objcect has a new key-value pair. furthermore: if you want easier access further on you can use this as well:


    return {
              ...user,
             id:action.payload.id,
             name:action.payload.name,
             address:action.payload.address

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