Home > Back-end >  How to save an object in redux?
How to save an object in redux?

Time:02-21

I build an app in React with Redux and I try to send to my state an object and I try to save it in 'thisUser' but I don't know how to write that 'return' because mine doesn't work.

My Redux state:

const initialState = {
    thisUser: {}
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/addUser':
            return { ...state, thisUser: { ...state.thisUser, ...action.payload} }  //the problem
        default:
            return state
    }
}

Dispatch method:

dispatch({ type: "users/addUser", payload: new_user });

Can you tell me how to write that return, please?

CodePudding user response:

If you want to append new user then why are you using object type. You should use Array Type thisUser.

const initialState = {
  thisUser: []
}

export function usersReducer(state = initialState, action) {
   switch (action.type) {
      case 'users/addUser':
          return { ...state, thisUser: [ ...state.thisUser,action.payload ] }  
      default:
          return state
  }
}

Or

If you want to save only single user object then change only that line in your code:

   return { ...state, thisUser: action.payload }  

CodePudding user response:

It's better to use an array type for if you have a list of users .

If you have a case when you need to use an object just change the brackets [ ] on my code to curly braces { } .

const initialState = {
    thisUser: [],
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/addUser':
            return { ...state, thisUser: [ ...state.thisUser, ...action.payload]}
        default:
            return state
    }
}  
  • Related