-1

My reducer is as follows:

    export const favorites = (state = {
    favorites: [],
    countFavorite: [],
    }, action) => {
        switch (action.type) {
            case ActionTypes.ADD_FAVORITE:
                return { ...state, favorites: action.payload };

        case ActionTypes.COUNT_FAVORITE:
            return { ...state, countFavorite: [...state.countFavorite, action.payload] };
        default:
            return state;
    }
};

currents I get the following with the old state and the new state:

enter image description here

I would like for the new object to override the existing object with the same key in the array, any help would be very appreciated

Cho Cho
  • 159
  • 3
  • 12

2 Answers2

1

The first, you should check the key exists, then add more item:

switch (action.type) {
    case ActionTypes.ADD_FAVORITE:
        return { ...state, favorites: action.payload };

    case ActionTypes.COUNT_FAVORITE: {
        let key = Object.keys(action.payload)[0];
        return { ...state, countFavorite: [...state.countFavorite.filter(fa => Object.keys(fa)[0] !== key), action.payload] };
    }
    default:
        return state;
}
Ryan Nghiem
  • 2,417
  • 2
  • 18
  • 28
0

In this case, you need to use Array.filter to only filter the object that is the same ID as the one in your action.payload out from the array, and then fill in the action.payload.

That should look like this.

case ActionTypes.COUNT_FAVORITE:
  return { ...state, countFavorite: [ ...state.countFavorite.filter( fav => fav.id !== action.payload.id ), action.payload] };

You can replace the ID with any unique identifier within the object. This way you can omit out the object that you want to replace with the newer one.

Fred A
  • 1,602
  • 1
  • 24
  • 41