Welcome to part-9 of the series. You can find part-8 here. We will learn about Async-actions using a react-redux app in this part.
The logic will be quite similar to the one we did in our redux app. Our application will fetch a list of users from an API end point and store it in the redux store.
So, go ahead and create a new file UserContainer.js inside the components folder. Put the basic content in it as of now.
Now, create a new folder user inside the redux folder. Inside it create a file userTypes.js and put the below content in it.
Now, create the file userActions.js inside the same user folder. It will contain our three actions of fetchUsersRequest, fetchUsersSuccess and fetchUsersFailure.
Now, create the file userReducer.js inside the same user folder. It is almost similar to what we made in the redux application. Here, when the user request is send we are making the loading as true. Then we will receive the payload or error from the API endpoint and depending on it we will populate the users array or the error string.
Now, it’s time to include the action creators in the index.js file.
Now, we need to include the userReducer in the combine reducer function. So, we will include it in the rootReducer.js file.
Redux Thunk Get Request
To make the get request and use the redux thunk middleware, we need to first install two packages of axios and redux-thunk. So, open your terminal and npm install both of them.
Now, we will apply the redux-thunk middleware to our store. We need to first import it and add it in the applyMiddleware function in the store.js file.
Next, head back to userActions.js to create our fetchUsers function. Here, we are first importing axios. After that inside the fetchUsers(), wew are first dispatching the fetchUsersRequest and then the axios request to the jsonplaceholder endpoint. Depending on the success or failure, we are dispatching the fetchUsersSuccess and fetchUsersFailure functions.
These will in-turn be received by the reducer function
Next, we will update the UserContainer.js file. Here, we have the usual mapStateToProps and mapDispatchToProps from where we are receiving the user state and dispatching the fetchUsers().
Inside the UserContainer, we are using useEffect to dispatch the fetchUsers once. Now, in the return statement we are using ternary operator to get to the users array and then displaying it.
We also need to include fetchUsers in the index.js file.
Now, in App.js show the component UserContainer
Now, back in localhost we can see the users.
This completes our react-redux series.
You can find code till here in this github repo.