Frallen
Frallen

Reputation: 443

Replace/update data in Switch case

The action data contains an array, I want, according to the id, to replace a specific array with new data. But it turns out that instead of updating one array, I get 3 array elements that contain other arrays.

Other records that do not match by id should remain the same

 case UpdateOneBank:
      return {
        ...state,
        data: state.data.map((p) => p._id === action.data._id?action.data:state.data),}

data state old data state

New data New data Update only one array, not to add 3 in to 2 remain arrays enter image description here

Upvotes: 1

Views: 462

Answers (2)

Aditya V
Aditya V

Reputation: 578

case UpdateOneBank:
  return {
    ...state,
    data: state.data.map((p) => p._id === action.data._id?action.data:p),}

Try this

You were returning the entire data in else condition, not an item of map.

Upvotes: 1

Himanshu Singh
Himanshu Singh

Reputation: 1953


Solution

   case UpdateOneBank:
        return {
           ...state,
           data: state.data.map((originalValue) => originalValue._id === action.data._id?  action.data:  originalValue),}

Error

Instead of doing this:

case UpdateOneBank:
      return {
        ...state,
        data: state.data.map((originalValue) => originalValue._id === action.data._id?  action.data:  state.data),}

Reason

Note: Everytime you are entering in else condition, you are pushing/returning your own state.data array

Upvotes: 1

Related Questions