Next, we are going to define the reducer function in a similar way that we did for the user state:
- 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) {
- 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 ]
- 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.