I already have a switch case statement in my reducer. How do I add an extra if condition in reducer?

Viewed 637

Using React-Redux-Thunk... I am trying to understand the best way to handle this use case in my reducer. On inserting a new searchterm in the database, I need to update my state ( which is a json summary of top searches ( key"value- searchterm:count). My objective is to add 1 to the count if my serachterm key exists else create a new key:value with "serachterm":1

How do i code this in my reducer

export default function topSearchReducer(state = {topSearches: []}, action) {
  console.log('action', action);
  console.log('Inside Top Search reducer state', state);
  switch (action.type) {
    case 'FETCH_TOP_SEARCHES':
      return {topSearches: action.payload}
    case 'UPDATE_TOP_SEARCH'
       if(action.searchterm in state.topSearches[0]){
         console.log( 'FOUND IN OBJECT!');
       }
    default:
      return state
  }
};
1 Answers

As I understand you correctly, EACH ITEM of your topSearches array is an OBJECT - a map, where key is searchTerm and value is count. I don't understand what you have in the array as you are checking only the first item of the array (topsearches[0]), but ok, try this:

case 'UPDATE_TOP_SEARCH':
    return {
        ...state,
        topSearches: [
            // update first item of array
            {
                // copy the previous state of map
                ...state.topSearches[0],
                // update item of map -
                // if searchterm was already there increase the count, otherwise add value 1
                [action.searchterm]: (
                    action.searchterm in state.topSearches[0] ?
                        state.topSearches[0][action.searchterm] + 1 :
                        1
                )
            },
            // just put shallow copy of all other items
            ...state.topSearches.slice(1)
        ]
    }
Related