FullStack Labs

Please Upgrade Your Browser.

Unfortunately, Internet Explorer is an outdated browser and we do not currently support it. To have the best browsing experience, please upgrade to Microsoft Edge, Google Chrome or Safari.
Upgrade
Welcome to FullStack Labs. We use cookies to enable better features on our website. Cookies help us tailor content to your interests and locations and provide many other benefits of the site. For more information, please see our Cookies Policy and Privacy Policy.

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

Written by 
,
Angular to React.js - Async Actions (Part 4 of 6)
blog post background
Recent Posts
The Benefits of Using a CSS Preprocessor
Diving Into OpenAI's ChatGPT API
Tips for effective Cross-Training Agile software and operations teams

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.

Table of contents

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.

-- CODE language-jsx keep-markup --
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',
};

exportdefault 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

-- CODE language-jsx keep-markup --
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.

-- CODE language-jsx keep-markup --
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';

Finally, apply the imported thunk on line 34.

-- CODE language-jsx keep-markup --
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.

-- CODE language-jsx keep-markup --
exportconst 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.

  • Go to store/reducers/cart.js.
  • Edit the initial state referencing the code below.

-- CODE language-jsx keep-markup --
const initialState = {
  items: [],
  shippingPrices: [],
  shippingPricesLoading: false,
  shippingPricesError: {},
};

  • Add the following action type cases to the reducer’s switch block.

-- CODE language-jsx keep-markup --
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.

-- CODE language-jsx keep-markup --
import React from "react";
import * as utils from "../utils";

const Shipping = ({ prices }) => {  
  return (  
    <div classname="app-cart"></div>
      <h3>Shipping Prices</h3>    
      {prices.map(shipping => (      
        <div key="{shipping.id}" classname="shipping-item"></div>
          <span>{ shipping.username }</span>        
          {<span>{ utils.currency(shipping.id) }</span>}      
            
       ))}  
    
   );
};

exportdefault Shipping;

Add styles for .app-cart and .shipping-item to the style.css file if they don’t already exist.

-- CODE language-jsx keep-markup --
/* 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.

-- CODE language-jsx keep-markup --
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}">;</shippingprices>
}

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.

  • Go to index.js.
  • Import the shipping container.

-- CODE language-jsx keep-markup --
import ShippingPricesContainer from './containers/ShippingPrices';

  • Include the route in the list.

-- CODE language-jsx keep-markup --
<route exact="" path="/shipping" component="{ShippingPricesContainer}"></route>

  • Go to the components/cart.js and verify the component includes a link to /shipping.

-- CODE language-jsx keep-markup --
<link to="/shipping">Shipping Prices

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.

Written by
People having a meeting on a glass room.
Join Our Team
We are looking for developers committed to writing the best code and deploying flawless apps in a small team setting.
view careers
Desktop screens shown as slices from a top angle.
Case Studies
It's not only about results, it's also about how we helped our clients get there and achieve their goals.
view case studies
Phone with an app screen on it.
Our Playbook
Our step-by-step process for designing, developing, and maintaining exceptional custom software solutions.
VIEW OUR playbook
FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project.
Engagements start at $75,000.

company name
name
email
phone
Type of project
How did you hear about us?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.