A JavaScript framework that allows rapid development of native Android and IOS apps.
A JavaScript framework maintained by Facebook that's ideal for building complex, modern user interfaces within single page web apps.
A server side programming language known for its ease of use and speed of development.
A lightweight and efficient backend javascript framework for web apps.
An interpreted high-level programming language great for general purpose programming.
A JavaScript framework maintained by Google that addresses many of the challenges encountered when building single-page apps.
A JavaScript framework that allows developers to build large, complex, scalable single-page web applications.
A progressive JavaScript framework known for its approachability, versatility, and performance.
View a sampling of our work implemented using a variety of our favorite technologies.
View projects implemented using this javascript framework ideal for building complex, modern user interfaces within single page web apps.
View projects implemented using this framework that allows rapid development of native Android and IOS apps.
View projects implemented using this backend javascript framework for web apps.
View projects implemented using this high-level programming language great for general purpose programming.
View projects implemented using this server side programming language known for its ease of use and speed of development.
Learn more about our current job openings and benefits of working at FSL.
Detailed reviews and feedback from past and current clients.
Detailed profiles for each member of our team.
Our step-by-step process for designing and developing new applications.
Get answers to the questions most frequently asked by new clients.
Learn about our company culture and defining principles.
A high level overview of FullStack Labs, who we are, and what we do.
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.
store/actions/cart.js
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.
index.js
.applyMiddleware
.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.
store/reducers/cart.js
.
const initialState = {
items: [],
shippingPrices: [],
shippingPricesLoading: false,
shippingPricesError: {},
};
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:
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
shippingPrices.js
file inside the components folder.
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.
shippingPrices.js
in the containers folder.
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.
index.js
.
import ShippingPricesContainer from './containers/ShippingPrices';
<Route exact path="/shipping" component={ShippingPricesContainer} />
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
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.
We’d love to learn more about your project. Contact us below for a free consultation with our CEO.
Projects start at $25,000.
A JavaScript framework maintained by Google that addresses many of the challenges encountered when building single-page apps.
A JavaScript framework that allows developers to build large, complex, scalable single-page web applications.
A lightweight and efficient backend javascript framework for web apps.
An interpreted high-level programming language great for general purpose programming.
A JavaScript framework maintained by Facebook that's ideal for building complex, modern user interfaces within single page web apps.
A JavaScript framework that allows rapid development of native Android and IOS apps.
A server side programming language known for its ease of use and speed of development.
A progressive JavaScript framework known for its approachability, versatility, and performance.
View a sampling of our work implemented using a variety of our favorite technologies.
View projects implemented using this backend javascript framework for web apps.
View projects implemented using this high-level programming language great for general purpose programming.
View projects implemented using this javascript framework ideal for building complex, modern user interfaces within single page web apps.
View projects implemented using this framework that allows rapid development of native Android and IOS apps.
View projects implemented using this server side programming language known for its ease of use and speed of development.
Learn more about our current job openings and benefits of working at FSL.
Detailed reviews and feedback from past and current clients.
Detailed profiles for each member of our team.
Our step-by-step process for designing and developing new applications.
Get answers to the questions most frequently asked by new clients.
Learn more about FullStack Lab’s Mission, Vision, & Company Values.
A high level overview of FullStack Labs, who we are, and what we do.