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_1
folder to a newChapter06_2
folder by executing the following command:$ cp -R Chapter06_1 Chapter06_2
- Open the new
Chapter06_2
folder in VS Code. - First, edit
src/reducers.js
and define a newFETCH_POSTS
action, 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...