Ravi K
Ravi K

Reputation: 125

How to destruct object in reducer (REACT)

I have the following userData in state

userData : {
 isValidCheckup: true,
 accounts: {
  userAccount: [
    {
      accountType: 'checkings',
      includeInCheckup: false
    },
    {
      accountType: 'checkings',
      includeInCheckup: false
    }
  ]
}

Now, I have a reducer to handle manipulation of above data. Note: I only want to update includeInCheckup field. Depending on the accountType recieved as a payload to the reducer.

Here is the reducer function I am using

case UPDATE_USER_DATA: {
  const { field, value } = action.payload; // field='checkings', value=true
  return {
   ...state,
   userData: {
     ...state.userData
   }
  }

} 

As you can see, I am getting field='checkings', value=true from the payload to the reducer. How can I specifically update this value to the includeInCheckup property based on the field value.

Can someone please shed some light.

Upvotes: 0

Views: 421

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

When I get field as 'checkings', I update the first element of array 'userAccount' and when I get field as 'savings, I will update the second element of array.

For example state, I am assuming userAccount[0] is a checking account type, and userAccount[1] is a savings account type, and the array will always be length 2.

userData : {
 isValidCheckup: true,
 accounts: {
  userAccount: [
    {
      accountType: 'checkings',
      includeInCheckup: false
    },
    {
      accountType: 'savings',
      includeInCheckup: false
    }
  ]
}

Copy each level of state that is being updated, and then update the property by creating a new object/array reference. You can simply map the userAccount array and check if the account type matches that of the action payload field, and update the includeInCheckup property.

case UPDATE_USER_DATA: {
  const { field, value } = action.payload; // field='checkings', value=true
  return {
    ...state,
    userData: {
      ...state.userData,
      accounts: {
        ...state.userData.accounts,
        userAccount: state.userData.accounts.map((account) =>
          account.accountType === field
            ? {
                ...account,
                includeInCheckup: value
              }
            : account
        )
      }
    }
  };
}

Upvotes: 2

Related Questions