Home > Back-end >  How to edit userAccount in an object in an Array
How to edit userAccount in an object in an Array

Time:11-19

please help me with this issue.

I'm making a register form and then user can edit their infomation by Redux, I'm having an issue with editing useraccount infomation (such as name, email, pass...)

I have tried with my code below, but it return an undefined state and nothing changed. I have an initialState like this:

const initialState = {
  userAccounts: [
    {
      id: new Date().getTime(),
      fullname: 'userName',
      email: 'userEmail',
      pass: 'userPass',
    },
  ],
};

here is my action and reducer:

export const editAccount = (param) => (
    {
        type: EDIT_ACCOUNT,
        payload: param
    }
)



const registerReducer = (state = initialState, action) => {
  
  switch (action.type) {
      
        case REGISTER:
            return {
                ...state,
                userAccounts: [...state.userAccounts, action.payload],
            };
            
        case EDIT_ACCOUNT:
            return state.userAccounts.map((account, i) => {
                if (account.id === action.payload.id) {
                    return {
                      ...state.userAccounts[i],
                      fullname: action.payload.fullname
                    };
                }
            });
        default:
        return state;

  }
};

Here is my dispatch code from the edit screen

 const handleChangeInfo = () => {
      let accIndex = userAccounts.findIndex(item => item.fullname === params.name)
      dispatch(editAccount({
        id: userAccounts[accIndex].id,
        fullname: value,
      }))
      navigation.goBack()
  }

CodePudding user response:

You may try this in your registerReducer

case EDIT_ACCOUNT:
let userArr = [];
state.userAccounts.map((account, i) => {
  if (account.id === action.payload.id) {
    userArr.push({
      ...account,
      fullname: action.payload.fullname
    })
  } else {
    userArr.push(account);
  }

});
return {
  ...state,
  userAccounts: [...userArr],
};
  • Related