Angular to React.js - Async Actions (Part 4 of 6)

Written by Cristian Marquez

Welcome to the fourth part of my Angular to React series. Previously, we integrated a state management system using the Redux library. Today, we will focus on asynchronous actions.


In our app’s current state, all actions executed by the user are fully synchronous. Each time an action is dispatched the state is updated immediately. However, if you try to make a call to the back end with a synchronous action, the UI will freeze as the app waits for a response from the database.


To avoid these pauses, we will need to update our synchronous actions to asynchronous actions. Asynchronous actions allow an app to handle requests with variable response times without blocking the main thread.


In this tutorial, we will create a new set of asynchronous actions to display a dynamic list of shipping prices. Then we will create a view to display the prices, and connect the prices to our store.


The starter kit for the app can be found here.


Creating new action types


First, we need to define the names of our new asynchronous actions inside the store/action-types/cart.js file.

    
const CartTypes = {
 ADD_TO_CART: 'ADD_TO_CART',
 CLEAR_CART: 'CLEAR_CART',
 GET_SHIPPING_PRICES_START: 'GET_SHIPPING_PRICES_START',
 GET_SHIPPING_PRICES_SUCCESS: 'GET_SHIPPING_PRICES_SUCCESS',
 GET_SHIPPING_PRICES_FAIL: 'GET_SHIPPING_PRICES_FAIL',
};
 
export default CartTypes;
    
  

Synchronous actions require only two action types, because an action will either succeed or fail immediately. Asynchronous actions require three action types, because we do not know when our action will succeed or fail. Therefore, we need an additional action type to let the app know the request is waiting for a response. Now the app can update the UI accordingly.


Creating actions


Now, we need to generate the actions themselves.

  1. Go to store/actions/cart.js
  2. Create three actions using the three action types from above.
            
    const getShippingPricesStarts = () => {
     return {
       type: types.GET_SHIPPING_PRICES_START,
     };
    };
     
    const getShippingPricesSuccess = shippingPrices => {
     return {
       type: types.GET_SHIPPING_PRICES_SUCCESS,
       shippingPrices,
     };
    };
     
    const getShippingPricesError = error => {
     return {
       type: types.GET_SHIPPING_PRICES_FAIL,
       error,
     };
    };
          
        

Aside from a few minor differences, the process for creating a synchronous action and an asynchronous action are identical up to this point.


In the previous tutorial, we were able to handle synchronous actions directly in components. Asynchronous actions, however, are more complicated, and should not be handled directly in a component. To efficiently reuse our async function, best practices suggest abstracting the functionality into a reusable function that can be called from any component.


To accomplish this we need to be able to dispatch actions from an async function. We can get this functionality using the redux-thunk middleware.


Before we can create our reusable function, we need to be able to dispatch actions from an async function. We can leverage the redux-thunk library to dispatch a redux action using the dispatch param available inside a promise.

  1. Go to index.js.
  2. Update line three to import applyMiddleware.
  3. Update line four to import thunk from redux-thunk.
    
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
    
  

Finally, apply the imported thunk on line 34.

    
const store = createStore(rootReducer, applyMiddleware(thunk));
    
  

Now that we’ve set up redux-thunk, we can prepare our function. Create an exported javascript function referencing the code below.

    
export const getShippingPrices = () => {
 return async dispatch => {
   try {
     dispatch(getShippingPricesStarts());
     const httpResponse = await axios.get(
       'https://jsonplaceholder.typicode.com/users'
     );
 
     dispatch(getShippingPricesSuccess(httpResponse.data));
   } catch (error) {
     dispatch(getShippingPricesError(error));
   }
 };
};
    
  

To initiate the async request, we need to use a promise-based HTTP client. For this tutorial we will be using Axios, but you could also use fetch or request-promise.


Note: Angular’s tutorial mocks the response using a local JSON file. Due to Stackblitz’s limitations, we won't be able to have a local JSON file in a React project. To make an async call with Stackblitz we will use https://jsonplaceholder.typicode.com/


The response is stored in the variable httpResponse. If httpResponse doesn't return an error, we will dispatch the getShippingPricesSuccess action with the shipping price data. If the async request fails, we will dispatch the getShippingPricesError action.


Creating the reducer


With all of the actions in place, it’s time to generate the reducer.

  1. Go to store/reducers/cart.js.
  2. Edit the initial state referencing the code below.
            
    const initialState = {
     items: [],
     shippingPrices: [],
     shippingPricesLoading: false,
     shippingPricesError: {},
    };
    
            
          
  3. Add the following action type cases to the reducer’s switch block.
            
    case types.GET_SHIPPING_PRICES_START: {
        return {
          ...state,
          shippingPrices: [],
          shippingPricesError: {},
          shippingPricesLoading: true,
        };
      }
    
    case types.GET_SHIPPING_PRICES_SUCCESS: {
      const { shippingPrices } = action;
      return {
        ...state,
        shippingPrices,
        shippingPricesLoading: false,
      };
    }
    
    case types.GET_SHIPPING_PRICES_FAIL: {
      const { error } = action;
    
      return {
        ...state,
        shippingPricesError: error,
        shippingPricesLoading: false,
      };
    }
            
          

In the initial states, we introduce three new states: 1) The shipping prices array will hold the collection of items returned by the server. 2) A loading flag to inform the UI if the async action is in progress. 3) A variable to store the error generated in the server.


The async types introduce three new potential values on the app’s state:

  1. An array to hold shipping prices returned from the server.
  2. A boolean to inform the UI that the async action is still in progress.
  3. A value to store any errors generated by the API.

We introduced three new cases to the reducer, one for each action type that will be executed by the dispatch method. When the action starts, we clear any shipping prices and errors, and set shippingPricesLoading to be true. If the response is a failure, shippingPricesLoading is set to false and all errors are sent the shippingPricesError object. If the response succeeds, we also set shippingPricesLoading to false and add the shipping prices to the shippingPrices array.


Creating the shipping prices view

  1. Create shippingPrices.js file inside the components folder.
  2. Copy and paste the code below to create a component that receives the list of prices as a prop, and returns the layout using JSX.
            
    import React from "react";
    import * as utils from "../utils";
     
    const Shipping = ({ prices }) => {
     
     return (
       <div className="app-cart">
         <h3>Shipping Prices</h3>
         {prices.map(shipping => (
           <div key={shipping.id} className="shipping-item">
             <span>{ shipping.username }</span>
             {<span>{ utils.currency(shipping.id) }</span>}
           </div>
         ))}
       </div>
     );
    };
     
    export default Shipping;
            
          
    Add styles for .app-cart and .shipping-item to the style.css file if they don’t already exist.
            
    /* Checkout Cart, Shipping Prices */
     
    .cart-item, .shipping-item {
       width: 100%;
       min-width: 400px;
       max-width: 450px;
       display: flex;
       flex-direction: row;
       justify-content: space-between;
       padding: 16px 32px;
       margin-bottom: 8px;
       border-radius: 2px;
       background-color: #EEEEEE;
    }
            
          

Creating the container


To connect the async actions, we will use the same high order component used in the previous article. Now, we need to add a second parameter of mapDispatchToProps to specify the actions.

  1. Create a file named shippingPrices.js in the containers folder.
  2. Add the code below to introduce a new parameter into the connect function.
            
    import React from 'react';
    import { connect } from 'react-redux';
     
    import ShippingPrices from '../components/ShippingPrices';
     
    import * as actions from '../store/actions/cart';
     
    const ShippingPricesContainer = (props) => {
     const { prices, getShippingPrices, loading } = props;
     
     return <ShippingPrices prices={prices} getShippingPrices={getShippingPrices} />;
    }
    const mapStateToProps = state => {
     return {
       prices: state.cart.shippingPrices
     };
    };
     
    const mapDispatchToProps = dispatch => {
     return {
       getShippingPrices: () => dispatch(actions.getShippingPrices()),
     };
    };
     
    export default connect(
     mapStateToProps,
     mapDispatchToProps
    )(ShippingPricesContainer);
    
            
          
    This parameter will return an object with all the actions available in the component.

Update the router


Our last step is to display the shipping prices in the React App.

  1. Go to index.js.
  2. Import the shipping container.
            
    import ShippingPricesContainer from './containers/ShippingPrices';
            
          
  3. Include the route in the list.
            
    <Route exact path="/shipping" component={ShippingPricesContainer} />
            
          
  4. Go to the components/cart.js and verify the component includes a link to /shipping.
            
    <Link to="/shipping">Shipping Prices</Link>
            
          

Now when you navigate to /shipping the app will display a list of products with the available prices.



Solutions

  1. The Angular solution to this tutorial can be found here.
  2. The React solution to this tutorial can be found here.

What's next?


So far, we have covered setup, routing, data management, and async actions. In the final parts of this Angular-to-React series, we will discuss form management and deployment.


---
At FullStack Labs, we pride ourselves on our ability to push the capabilities of cutting-edge frameworks like React. Interested in learning more about speeding up development time on your next project? Contact us.

Let’s Talk!

We’d love to learn more about your project. Contact us below for a free consultation with our CEO.
Projects Start at $25,000.

FullStack Labs
This field is required
This field is required
Type of project
Reason for contact:
How did you hear about us? This field is required