Reducers

Now, we still need to define the function that handles these state changes. Such a function is known as a reducer function. It takes the current state and action as arguments, and returns a new state.

If you are aware of the Redux library, you will already be very familiar with the concept of state, actions, and reducers.

Now, we are going to define our reducer function:

  1. We start with the function definition of our reducer:
function reducer (state, action) {
  1. Then, we check for action.type using a switch statement:
    switch (action.type) {
  1. Now, we are going to handle the TOGGLE_EXPAND action, where we simply toggle the current expandPosts state:
        case 'TOGGLE_EXPAND':
return { ...state, expandPosts: !state.expandPosts }
  1. Next, we are going to handle the CHANGE_FILTER action. Here, we first need to check if all is set to true, and, in that case, simply set our filter to the 'all' string:
        case 'CHANGE_FILTER':
if (action.all) {
return { ...state, filter: 'all' }
}
  1. Now, we have to handle the other filter options. First, we check if the filter variable is already an object. If not, we create a new one. Otherwise, we use the existing object:
            let filter = typeof state.filter === 'object' ? state.filter : {}
  1. Then, we define the handlers for the various filters, allowing for multiple filters to be set at once, by not immediately returning the new state:
            if (action.fromDate) {
filter = { ...filter, fromDate: action.fromDate }
}
if (action.byAuthor) {
filter = { ...filter, byAuthor: action.byAuthor }
}
  1. Finally, we return the new state:
            return { ...state, filter }
  1. For the default case, we throw an error, because this is an unknown action:
        default:
throw new Error()
}
}
Throwing an error in the default case is different to what is best practice with Redux reducers, where we would simply return the current state in the default case. Because React Reducer Hooks do not store all state in one object, we are only going to handle certain actions for certain state objects, so we can throw an error for unknown actions.

Now, our reducer function has been defined, and we can move on to defining the Reducer Hook.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.213.128