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

194
Visualizações
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 Respostas
Responde à pergunta

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