0

I have an object like this in json:

let state = {
  authenticationObj: {
    "isAuthenticating": true, "isAuthentic": false, "subscriberId": "NA", "username": "NA",
    "firstName": "NA", "lastName": "NA", "enabled": "1", "email": "NA", isAuthorized: false
  }, lastPasswordCheckStatus:undefined }

Now I want to just change an item in authenticationObj lets say email. I know I should use ... so if I was going to change lastPasswordCheckStatus I would do it this way:

state = {
  ...state,
  lastPasswordCheckStatus: action.payload.lastPasswordCheckStatus
}

So far so good. But how can I change the email inside authenticationObj and keep all the other attributes value such as lastPasswordCheckStatus and firstname and etc?

Alexander Kahoun
  • 2,458
  • 24
  • 36
Hamed Minaee
  • 2,480
  • 4
  • 35
  • 63
  • state = { ...state, authenticationObj: { ...authenticationObj, "email" : [your new email] } }. Hope it works – dnp1204 Mar 29 '18 at 14:48
  • Possible duplicate of [How to update a nested state in React](https://stackoverflow.com/questions/43040721/how-to-update-a-nested-state-in-react) – Shubham Khatri Mar 29 '18 at 16:16

1 Answers1

1

You can pass more than one property when using the spread syntax like that. You just need to keep destructuring as you go.

let state = {
  authenticationObj: {
    "isAuthenticating": true, 
    "isAuthentic": false, 
    "subscriberId": "NA", 
    "username": "NA",
    "firstName": "NA", 
    "lastName": "NA", 
    "enabled": "1", 
    "email": "NA", 
    isAuthorized: false
  }, 
  lastPasswordCheckStatus: undefined
};

state = { 
  ...state, 
  lastPasswordCheckStatus: action.payload.lastPasswordCheckStatus,
  authenticationObj: {...state.authenticationObj, email: "newEmailValue"} 
}

At a certain point it will start to get unreadable and you can break it apart to something like this

const newAuthenticationObj = {
  ...state.authenticationObj,
  email: "newEmailValue"
}
state = {
  ...state,
  lastPasswordCheckStatus: action.payload.lastPasswordCheckStatus,
  authenticationObj: newAuthenticationObj
}

Take a look at the destructuring documentation on MDN

Alexander Kahoun
  • 2,458
  • 24
  • 36