React Lesson 13 Part 2: Asynchronous actions

React Lesson 13 Part 2: Asynchronous actions

React Lesson 13 Part 2: Asynchronous actions

Hey everyone. In the previous article, we used Redux Thunk and learned how to structure actions for asynchronous calls. Now we will update reducer to handle them and then dispatch them from Articles.js. Let’s update the reducer first.

We are not getting articles from fixtures.js now. That means we will initially have an empty array in articles instead of normalizedArticles and defaultArticles will look something like this:

Now update the initial state:

Having the articles added here, we receive a structure that can be reused from one reducer to another, which means entities will contain articles and comments. Our code below will also be changed:

As you can see, we have slightly updated our INITIAL_STATE which means we have to update the containers where we are consuming this state. Let’s start with Filters.js:

Now update containers/Articles.js. We are going to call action where we are fetching all the articles from the API and update state to get those articles from entities:

In the render function, we are checking isFetching flag which we defined earlier. While isFetching is true, we know the request is in process and we can show a loading text or spinner while we get our data. Once we have the data isFetching will be updated to false and render function will render the ArticleList on screen.

That’s it. We have successfully connected actions with reducer and can fetch articles from the API. I hope you understood how to use thunk for asynchronous calls in actions. Go ahead and check it. Lesson code can be found in the GitHub repo.

 

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

React Lesson 15: Checking Homework progress from Lesson 14

Today, we are going to cover homework from Lesson 14 and add comment API to load comments. ...

React Lesson 14: Redux Thunk Deep Dive

In this lesson, we will understand the internals of Redux Thunk and the use cases where we should use ...

React Lesson 13. Part 1: Asynchronous actions

Our topic for today deals with asynchronous actions. We will start to take our articles from API. As you have already noticed, we have a simple API ...

No comments yet

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy