React Hooks tutorials for beginners-9
Welcome to part-9 of the series. You can find part-8 here. We will learn to fetch data with useReducer hook in this part.
Fetch data with useReducer
For fetching data with useReducer, we will first install axios with below command in the terminal.
npm install --save axios
We will first look into the example of fetching data, with useState and then the same example with useReducer.
Create a new file DataFetching1.js inside the components folder. Here, we have done the necessary imports and after that we have three state variables, using useState.
Now, in the useEffect we are calling the API endpoint to return a single post. On success in the then block, we are setting the loading to false, post to response.data which is an object and error to an empty string.
Similarly, in the case of error in the catch block, we are setting the loading to false, post to empty object and error to an string.
Now, in the return statement, we are displaying the text Loading if loading is true or else the post.title. Also, if we get error we are displaying itr or elase null.
Now, include DataFetching1 in the App.js file.
Now, if we go to localhost we can see the post title. If we refresh and see closely, we can see the Loading text also.
To see the error code been executed, we need to misspelled in the url.
Now, back to localhost we can see the error.
Next, we will see how to do the same with useReducer and useEffect. Create a new file DataFetching2.js inside the components folder. Here, we have done the necessary imports and after that in initialState we are having the three states for loading, error and post.
Inside the reducer we have two cases, one for FETCH_SUCCESS and other for FETCH_FAILURE and both of them are changing the three states.
Now inside the DataFetching2 function, we are using the useReducer function which takes the reducer and initialState and get’s the state and dispatch. After that the useEffect is doing the API call and when it successfully receives the response, it dispatches the FETCH_SUCCESS and the payload top the reducer.
In the case of error, the FETCH_ERROR is dispatched to the reducer. Next, inside the return statement we are showing title or error depending on the state.
We have included DataFetching2 in the App.js file.
Now, on moving to localhost we can see the logic working as earlier.
This completes part-9 of the series. You can find part-10 here.
You can find the code for the same in this github repo.