Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!