Requesting resources using an Effect and a State/Reducer Hook
Before learning how to use a library to implement requests using Hooks, we are going to implement them manually, using an Effect Hook to trigger the request, and a State/Reducer Hook to store the result.
Fetching posts from the server
We are now going to implement a way to fetch posts by using an Effect Hook. Then, we will store it by extending the already defined Reducer Hook. Let’s get started:
- Copy the
Chapter06_1folder to a newChapter06_2folder by executing the following command:$ cp -R Chapter06_1 Chapter06_2 - Open the new
Chapter06_2folder in VS Code. - First, edit
src/reducers.jsand define a newFETCH_POSTSaction, which is simply going to return the new list of posts from the action:export function postsReducer(state, action) { switch (action.type) { case 'CREATE_POST': return [action.post, ...state] case 'FETCH_POSTS...