Defining the reducer

Next, we are going to define the reducer function in a similar way that we did for the user state:

  1. We start by editing src/App.js, and defining the reducer function there. The following code defines the postsReducer function:
function postsReducer (state, action) {
switch (action.type) {
  1. In this function, we are going to handle the CREATE_POST action. We first create a newPost object, and then we insert it at the beginning of the current posts state by using spread syntax, in a similar way to how we did it in the src/post/CreatePost.js component earlier:
        case 'CREATE_POST':
const newPost = { title: action.title, content: action.content, author: action.author }
return [ newPost, ...state ]
  1. For now, this will be the only action that we handle in this reducer, so we can now define the default statement:
        default:
throw new Error()
}
}

Now, the postsReducer function is defined, and we can move on to creating 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.16.69.143