A basic understanding of React and Java are needed to follow this tutorial.

Programming a shopping cart may not be as easy as you think. One of the greatest challenges is to synchronize the content of a user's shopping cart between devices or even browser tabs.

For example, a friend sends you, via a messaging app on your phone, the link to a great deal on the latest video game that you've been dying to get. You add the game to your shopping cart, but for some reason, you prefer to go through the checkout process on your desktop computer. You log into your account and that's when you realize that there's nothing in your shopping cart. You add the video game to the shopping cart again on your phone, but nothing appears on the other side. Have you experienced this before? Are you a developer that doesn't want your users to go through the same annoyance? If so, keep reading.

In this tutorial, we're going to build a simple realtime shopping cart, using Pusher to solve the synchronization issue we mentioned earlier. When an action like a quantity update or an item is removed from the Cart, a Pusher event will be sent so all the listening devices, windows or tabs can be synchronized accordingly.

The stack will be the following:

To keep things simple, we won't use a database. We'll keep a list of four products in memory, the app will only support one user, and the cart items will be stored in a web session.

The server will provide a REST API so the front-end can work just as a presentation layer with AJAX calls. For complex applications, the recommended way to do this is by using something like Redux. In fact, in the Redux documentation you can find a shopping cart example. However, once again, to keep things simple, we are going to issue all of our AJAX requests from the parent component using fetch.

In summary, our shopping cart will have the following functionality:

Choose the quantity to add a product to the shopping cart (if the product is already in the shopping cart, the quantity will be updated)

Remove a product from the shopping cart

Calculate the total when a product is added/updated/removed

Empty the shopping cart

This is how the final application will look:

This tutorial assumes prior knowledge of Java 8, Spring Boot/MVC and React. We will integrate Pusher into a Spring MVC REST API, create React components and hook them up with Pusher.

You can find the entire code of the application on Github.

Setting up Pusher

Create a free account at https://pusher.com/signup.

When you first log in, you'll be asked to enter some configuration options:

Enter a name, choose React as your front-end tech, and Java as your back-end tech. This will give you some sample code to get you started.

This won't lock you into a specific set of technologies, you can always change them. With Pusher, you can use any combination of libraries.

Then go to the App Keys tab to copy your App ID, Key, and Secret credentials - we'll need them later.

Setting up the application

One of the easiest ways to create a Spring Boot app is to use the project generator at https://start.spring.io/.

Go to that page and choose to generate a Maven project with the following dependencies:

Web

Thymeleaf

Enter a Group ID, an Artifact ID and generate the project:

Unzip the content of the downloaded file. At this point, you can import the project to an IDE if you want.

Now open the pom.xml file and add the Pusher library to the dependencies section:

<dependency> <groupId>com.pusher</groupId> <artifactId>pusher-http-java</artifactId> <version>1.0.0</version> </dependency>

The Java Back-end

Let's start with the com/pusher/web/IndexController class. It defines the root route ( / ) that shows an index template, passing the Pusher App Key and the channel name where the events will be published:

@Controller @SessionAttributes(GeneralConstants.ID_SESSION_SHOPPING_CART) public class IndexController { @RequestMapping(method=RequestMethod.GET, value="/") public ModelAndView index(Model model) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("index"); modelAndView.addObject("pusher_app_key", PusherConstants.PUSHER_APP_KEY); modelAndView.addObject("pusher_channel", PusherConstants.CHANNEL_NAME); if(!model.containsAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART)) { model.addAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART, new ArrayList<Product>()); } return modelAndView; } }

The @SessionAttributes annotation defines the identifier of an attribute that will be added to the session automatically when an object with the same identifier is added to the model object. This way, if a list of products (representing the shopping cart) is not in the session already, an empty one is created.

As this application supports only one user, the name of the channel is fixed. However, in a real application, the shopping cart of each user will use a different Pusher channel, so the name would have to be unique. But there's no problem, Pusher offers unlimited channels on all of its plans.

Then, we have the com/pusher/web/CartController class, where the REST API for our shopping cart is defined. First, we define the configure() method that is called after dependency injection is done to initialize the Pusher object and the list of products:

@RestController @SessionAttributes(GeneralConstants.ID_SESSION_SHOPPING_CART) public class CartController { private List<Product> products = new ArrayList<Product>(); private Pusher pusher; @PostConstruct public void configure() { pusher = new Pusher( PusherConstants.PUSHER_APP_ID, PusherConstants.PUSHER_APP_KEY, PusherConstants.PUSHER_APP_SECRET ); Product product = new Product(); product.setId(1L); product.setName("Office Chair"); product.setPrice(new BigDecimal("55.99")); products.add(product); product = new Product(); product.setId(2L); product.setName("Sunglasses"); product.setPrice(new BigDecimal("99.99")); products.add(product); product = new Product(); product.setId(3L); product.setName("Wireless Headphones"); product.setPrice(new BigDecimal("349.01")); products.add(product); product = new Product(); product.setId(4L); product.setName("External Hard Drive"); product.setPrice(new BigDecimal("89.99")); products.add(product); } ... }

Next, we define the endpoints to get, in JSON format, the list of products as well as the products in the shopping cart:

public class CartController { ... @RequestMapping(value = "/products", method = RequestMethod.GET, produces = "application/json") public List<Product> getProducts() { return products; } @RequestMapping(value = "/cart/items", method = RequestMethod.GET, produces = "application/json") public List<Product> getCartItems(@SessionAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART) List<Product> shoppingCart) { return shoppingCart; } ... }

A method to search for a product by its identifier in a list of products would be handy, so let's define one using the Java 8 Stream API to do it in a functional style:

private Optional<Product> getProductById(Stream<Product> stream, Long id) { return stream .filter(product -> product.getId().equals(id)) .findFirst(); }

This way, to add a product, we look for the product passed in the catalog of products (to see if it's a valid one) and then, if the product is in the shopping cart already, we update its quantity, otherwise, we added directly to the shopping cart, triggering an itemUpdated or itemAdded accordingly:

public class CartController { ... @RequestMapping(value = "/cart/item", method = RequestMethod.POST, consumes = "application/json") public String addItem(@RequestBody ItemRequest request, @SessionAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART) List<Product> shoppingCart) { Product newProduct = new Product(); Optional<Product> optional = getProductById(products.stream(), request.getId()); if (optional.isPresent()) { Product product = optional.get(); newProduct.setId(product.getId()); newProduct.setName(product.getName()); newProduct.setPrice(product.getPrice()); newProduct.setQuantity(request.getQuantity()); Optional<Product> productInCart = getProductById(shoppingCart.stream(), product.getId()); String event; if(productInCart.isPresent()) { productInCart.get().setQuantity(request.getQuantity()); event = "itemUpdated"; } else { shoppingCart.add(newProduct); event = "itemAdded"; } pusher.trigger(PusherConstants.CHANNEL_NAME, event, newProduct); } return "OK"; } ... }

Deleting a product from the shopping cart is similar. If the product is valid (if it exists in the catalog), we look for it on the shopping cart to remove it and trigger an itemRemoved event on Pusher:

public class CartController { ... @RequestMapping(value = "/cart/item", method = RequestMethod.DELETE, consumes = "application/json") public String deleteItem(@RequestBody ItemRequest request, @SessionAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART) List<Product> shoppingCart) { Optional<Product> optional = getProductById(products.stream(), request.getId()); if (optional.isPresent()) { Product product = optional.get(); Optional<Product> productInCart = getProductById(shoppingCart.stream(), product.getId()); if(productInCart.isPresent()) { shoppingCart.remove(productInCart.get()); pusher.trigger(PusherConstants.CHANNEL_NAME, "itemRemoved", product); } } return "OK"; } ... }

Finally, to empty the cart, we just replace the cart in the session with an empty list and trigger the cartEmptied Pusher event:

public class CartController { ... @RequestMapping(value = "/cart", method = RequestMethod.DELETE) public String emptyCart(Model model) { model.addAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART, new ArrayList<Product>()); pusher.trigger(PusherConstants.CHANNEL_NAME, "cartEmptied", ""); return "OK"; } ... }

React + Pusher

React thinks of the UI as a set of components, where you simply update a component's state, and then React renders a new UI based on this new state updating the DOM for you in the most efficient way.

The app's UI will be organized into five components, a header ( Header ), the cart ( Cart ), a component for each cart item ( CartItem ), the product list ( ProductList ), and a component for each product ( Product ):

The template for the index page just contains references to the CSS files, a page header, a div element where the UI will be rendered, the Pusher app key and channel name (passed from the server), and references to all the Javascript files the application uses:

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Real-time shopping cart with Pusher, Java, and React</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" /> <link rel="stylesheet" href="/css/style.css" /> </head> <body class="blue-gradient-background"> <nav class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="https://pusher.com"> <img class="logo" src="/images/pusher-logo.png" width="111" height="37"/> </a> </div> <p class="navbar-text navbar-right"><a class="navbar-link" href="http://pusher.com/signup">Create a Free Account</a></p> </div> </nav> <div id="app"></div> <!-- React --> <script src="https://unpkg.com/react@15.4.1/dist/react-with-addons.js"></script> <script src="https://unpkg.com/react-dom@15.4.1/dist/react-dom.js"></script> <script src="https://unpkg.com/babel-standalone@6.19.0/babel.min.js"></script> <!-- Libs --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.1/fetch.js"></script> <script src="https://js.pusher.com/4.0/pusher.min.js"></script> <!-- Pusher Config --> <script th:inline="javascript"> var PUSHER_APP_KEY = /*[[${pusher_app_key}]]*/ 'NA'; var PUSHER_CHANNEL_NAME = /*[[${pusher_channel}]]*/ 'NA'; </script> <!-- App/Components --> <script type="text/babel" src="/js/components/header.js"></script> <script type="text/babel" src="/js/components/cartItem.js"></script> <script type="text/babel" src="/js/components/cart.js"></script> <script type="text/babel" src="/js/components/product.js"></script> <script type="text/babel" src="/js/components/productList.js"></script> <script type="text/babel" src="/js/app.js"></script> </body> </html>

The application will be rendered in the div element with the ID app . The file static/js/app.js is the starting point for our React app:

var App = React.createClass({ ... }); ReactDOM.render(<App />, document.getElementById("app"));

Inside the App class, first, we define our state as arrays of cart items and products:

var App = React.createClass({ getInitialState: function() { return { items: [], products: [] }; }, ... }); ...

Then, we use the componentWillMount method, which is invoked once immediately before the initial rendering occurs, to set up Pusher and a variable to keep the cart total:

var App = React.createClass({ ... componentWillMount: function() { this.pusher = new Pusher(PUSHER_APP_KEY, { encrypted: true, }); this.channel = this.pusher.subscribe(PUSHER_CHANNEL_NAME); this.total = 0; }, ... }); ...

We subscribe to the channel's events in the componentDidMount method and get the catalog of products and any existing content of the shopping cart using fetch:

var App = React.createClass({ ... componentDidMount() { this.channel.bind('itemAdded', this.itemAdded); this.channel.bind('itemUpdated', this.itemUpdated); this.channel.bind('itemRemoved', this.itemRemoved); this.channel.bind('cartEmptied', this.cartEmptied); fetch('/products').then(function(response) { return response.json(); }).then(this.getProductsSuccess); fetch('/cart/items', { credentials: 'same-origin', }).then(function(response) { return response.json(); }).then(this.getCartItemsSuccess); } ... }); ...

The callbacks used when the products and cart items are fetched from the server just update the state of the component and calculate the cart total using the countTotal function:

var App = React.createClass({ ... getProductsSuccess: function(response) { this.setState({ products: response }); }, getCartItemsSuccess: function(response) { this.countTotal(response); this.setState({ items: response }); }, countTotal: function(newArray) { var temp = 0; newArray.forEach(function(item, index) { temp += (item.price * item.quantity); }); this.total = temp; }, ... }); ...

In the componentWillUnmount method, we unsubscribe from the Pusher events and in case the AJAX requests have not been completed at that point, we assign an empty function to the callbacks to do nothing when the component is unmounted:

var App = React.createClass({ ... componentWillUnmount: function() { this.channel.unbind(); this.pusher.unsubscribe(this.channel); this.getProductsSuccess = function() {}; this.getCartItemsSuccess = function() {}; }, ... }); ...

When an itemAdded event is received, the total is updated and the new item is added to a new array, which is used to update the state so React can re-render the components:

var App = React.createClass({ ... itemAdded: function(item) { var newArray = this.state.items.slice(0); newArray.push(item); this.countTotal(newArray); this.setState({ items: newArray, }); }, ... }); ...

Something similar happens with the itemUpdated and itemRemoved events, the difference is that the index of the item being referenced is looked up using the some function to update/remove it:

var App = React.createClass({ ... itemUpdated: function(item) { var newArray = this.state.items.slice(0); var indexToUpdate; this.state.items.some(function(it, index) { if(it.id === item.id) { indexToUpdate = index; return true; } }); newArray[indexToUpdate].quantity = item.quantity; this.countTotal(newArray); this.setState({ items: newArray, }); }, itemRemoved: function(item) { var newArray = this.state.items.slice(0); var indexToRemove; this.state.items.some(function(it, index) { if(it.id === item.id) { indexToRemove = index; return true; } }); newArray.splice(indexToRemove, 1); this.countTotal(newArray); this.setState({ items: newArray, }); }, ... }); ...

And, when the cart is emptied, we just update the state with an empty array. Notice how in all cases, we worked with a copy of the existing array, since React works best with immutable objects:

var App = React.createClass({ ... cartEmptied: function() { var newArray = []; this.countTotal(newArray); this.setState({ items: newArray }); }, ... }); ...

Finally, the render method shows the top-level components of our app:

var App = React.createClass({ ... render: function() { return ( <div className="container"> <Header /> <Cart items={this.state.items} total={this.total} /> <ProductList products={this.state.products} /> </div> ); } ... } ...

static/js/header.js is a simple component without state or properties that only renders the HTML for the page's title.

The Cart component (public/js/cart.js) takes the array of items to create an array of CartItem components and define an emptyCart function to call the API endpoint for that functionality:

var Cart = React.createClass({ emptyCart: function() { fetch('/cart', { credentials: 'same-origin', method: 'DELETE' }); }, render: function() { var itemsMapped = this.props.items.map(function (item, index) { return <CartItem item={item} key={index} /> }); var empty = <div className="alert alert-info">Cart is empty</div>; return ( <div className="row extra-bottom-margin"> <div className="col-xs-8 col-xs-offset-2"> <div className="panel panel-info"> <div className="panel-heading"> <div className="panel-title"> <div className="row"> <div className="col-xs-12"> <h5><span className="glyphicon glyphicon-shopping-cart"></span> Shopping Cart</h5> </div> </div> </div> </div> <div className="panel-body"> <div className="row"> <div className="col-xs-6"> <h6><strong>Product</strong></h6> </div> <div className="col-xs-6"> <div className="col-xs-4 text-center"> <h6><strong>Price</strong></h6> </div> <div className="col-xs-4 text-center"> <h6><strong>Quantity</strong></h6> </div> <div className="col-xs-4 text-center"></div> </div> </div> {itemsMapped.length > 0 ? itemsMapped : empty} </div> <div className="panel-footer">; <div className="row text-center"> <div className="col-xs-9"> <h4 className="text-right">Total <strong>${this.props.total}</strong></h4> </div> <div className="col-xs-3"> <button type="button" className="btn btn-info btn-sm btn-block" onClick={this.emptyCart} disabled={itemsMapped.length == 0}> Empty cart </button> </div> </div> </div> </div> </div> </div> ); } });

The CartItem component (static/js/cartItem.js) defines functions to remove the item from the shopping cart (passing its identifier) and render it:

var CartItem = React.createClass({ deleteItem: function() { fetch('/cart/item', { credentials: 'same-origin', method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: this.props.item.id, }) }); }, render: function() { var name = this.props.item.name; var id = this.props.item.id; var price = this.props.item.price; var quantity = this.props.item.quantity; return ( <div className="row cart-item"> <div className="col-xs-6"> <h6 className="product-name"><strong>{name}</strong></h6> </div> <div className="col-xs-6"> <div className="col-xs-4 text-center"> <h6>{price}</h6> </div> <div className="col-xs-4 text-center"> <h6>{quantity}</h6> </div> <div className="col-xs-4 text-center"> <button type="button" className="btn btn-link btn-xs" onClick={this.deleteItem}> <i className="fa fa-trash-o fa-lg"></i> </button> </div> </div> </div> ); } });

On the other hand, the ProductList component (static/js/productList.js) takes the array of products to create an array of Product components:

var ProductList = React.createClass({ render: function() { var productsMapped = this.props.products.map(function (product, index) { return <Product product={product} key={index} /> }); return ( <div className="row extra-bottom-margin"> {productsMapped} </div> ); } });

While the Product component defines quantity as its state, a function to call the API endpoint to add an item to the shopping cart and render a product:

var Product = React.createClass({ getInitialState: function() { return { quantity: 1 }; }, updateQuantity: function(evt) { this.setState({ quantity: evt.target.value }); }, addToCart: function() { fetch('/cart/item', { credentials: 'same-origin', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: this.props.product.id, quantity: this.state.quantity, }) }); }, render: function() { var name = this.props.product.name; var id = this.props.product.id; var price = this.props.product.price; return ( <div className="col-sm-3"> <div className="col-item"> <div className="photo"> <img src="http://placehold.it/200x150" className="img-responsive" alt="a" /> </div> <div className="info"> <div className="row"> <div className="price col-md-12"> <h5>{name}</h5> <h5 className="price-text-color">${price}</h5> </div> </div> <div className="separator clear-left"> <p className="section-qty"> <input className="form-control input-sm" type="text" value={this.state.quantity} onChange={this.updateQuantity} /> </p> <p className="section-add"> <button type="button" className="btn btn-link btn-xs" onClick={this.addToCart}> <i className="fa fa-shopping-cart"></i><span className="hidden-sm">Add to cart</span> </button> </p> </div> <div className="clearfix"></div> </div> </div> </div> ); } });

Finally, you can run the application either by executing the com.pusher.ShoppingCartApplication class on your IDE, or on the command line with:

$ mvn spring-boot:run

Additionally, on the command line, you can create a JAR file and execute it:

$ mvn package -DskipTests $ java -jar target/shopping-cart-0.0.1-SNAPSHOT.jar

Now, when you open http://localhost:8080/ in two browser windows at the same time, the actions made in one window should be reflected on the other one:

Conclusion

In this tutorial, we saw how to integrate Pusher into a Java back-end and a React front-end. As you can see, it is trivial and easy to add Pusher to your app and start adding new features. You can start on the forever free plan that includes 100 max connections, unlimited channels, 200k daily messages, and SSL protection. Signup now!

Remember that if you get stuck, you can find the final version of this code on Github or contact us with your questions.

Further reading