Writing a simple Async React Redux app in 20 minutes

Uncategorized

Note: This tutorial is designed for people, who’re already aware of the Flux based design process which react-redux enforces. In this tutorial we are going to simply call a backend API and retrieve some data from it using react-redux.

About the app we are building
Our application is pretty generic. It’s a display of a bunch of categories, clicking any of which loads posts from that category. To load posts we make a call to a backend API. To simulate errors in the API response, we also randomly make the call go to an incorrect url.

Mandatory demo first
Check out a demo of the app below. You can open it in a new tab with the browser console opened up to receive logs of previous and next states every time the state is changed.

 

So overall, there are going to be 2 main components in our app, namely categories and activecategory.

  • categorylist: Contains a list of categories, with a button to load data from that category.
  • activecategory: Displays posts from the selected category

PS: If you don’t really care about reading this and want to jump right into the code, here’s my repository for the whole thing: https://codesandbox.io/s/73llyql6lq . You’re welcome.

Step 1 : Planning + Writing our Actions

Our folder structure:

Planning our app’s actions. Since this is going to be an async application, we’d be needing at least 3 states.

  • API_CALL_STARTED/ FETCH_POSTS : The state once a user clicks a button that intiates the API call. We can use this state to show our loaders.
  • API_DATA_RETREIVED / RECEIVE_POSTS : The state once data is succesfully retreived from the backend
  • API_DATA_FAILED  /ERROR_GETTING_POSTS : The state to go into if we were unable to fetch data from the API.

actions/index.jsx

Actions file, is the main synchronous part of our application. It loads the posts from the API using the axios http library. Then uses Rx to convert it to an observable, this allows us to be notified when the library is done fetching it’s posts. We don’t really need Rx here, we can simply chain a function to get the response, don’t know why I used it here I guess it was just to look cooler.

The top 3 functions in the file are pretty self explanatory, they simply are action creators for the different actions we defined above. The main crux of this app is in the fetchPosts function. You might have noticed this function is also different from the above functions in terms of what it returns. It returns another function. Now for your action to return another function of this style (for async actions), you must remember to include the redux thunk middleware in your main file. What the middleware does is allow you to return a function with 2 parameters (dispatch and getState) . Once your action has completed whatever it had to do, you can simply call the dispatch function and pass in it the new action that you want to perform next as a parameter.  In our case we call it with dispatch(requestPosts(category)); . If you see the contents of requestPosts above, you’ll notice it’s payload has only 1 key of significance: fetching. This action basically notifies the activecategory container that a load process has initiated and it can now display a loader to the user.

Next, we do our thing (do a GET request) to either Reddit or Jsonplaceholder.typicode.com. All requests to Reddit result in an error, while the ones to Jsonplaceholder.typicode.com result in an actual result. For every click we use the Math.random function, if the output is > 0.5 we go to reddit (error) else jsonplaceholder (success). Next when the response arrives, we call the dispatch(receivePosts(category, res));  function.  Which transforms the response body and passes it to our categories container. The same goes for the error, except that we use our dispatch to call a different function.

 

Step 2 : Writing our containers

We will start with the categorylist container. As you can imagine, this container will be used to display a list of our categories. For now, we’ll simply display a list of hardcoded categories, we can write the contents of this list in our categories reducer. For the design of our little app, we’re using Shopify’s polaris design system’s components, because they look pretty good.

/containers/categorylist.jsx

So, here’s how our CategoryList component looks like:

As you can see the component itself is pretty simple, it simply gets a bunch of categories from the props and displays it to the user. At the end of the file, we call the famous mapStateToProps, simply for mapping our redux store’s categories to this component.

The other function matchDispatchToProps is another complex sounding function, but it’s really something simple. What it does is that it allows react-redux to call our function fetchPosts for us (since as part of the redux design, we can’t call it ourselves) and maps it to the properties of this component as well. Now all we have to do to call this function from our component is this.props.fetchPosts().

/containers/activecategory.jsx

This file, displays content depending upon the properties it receives.

 

Step 3 : Writing our reducers

/reducers/activecategory.reducer.jsx

Listens to state changes (all reducers receive notifications of all actions). We added a switch statement so we could only listen to actions we care about and then simply return the payload.

/reducers/categories.reducer.jsx

Pretty simple

 

Step 4 : Combining everything together

Next up we write up our App.js, wrap it in a provider and call it from our main index.

components/App.jsx

./index.jsx



Written by on September 28, 2017

More from the blog


GateSentry updates

Found some free time this weekend, decided to put it to use with some long needed updates to Read More


GateSentry Raspberry Pi : Updating the expired certificate

If you're using GateSentry's Raspberry Pi image, you might be seeing some certificate expiry Read More


Building a simple serverless CRUD app powered by Lambda and DynamoDB

Amazon web services has a very Read More