简体   繁体   中英

How to save an object in redux?

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?

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 }  

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM