Building simple Point of Sale system with Node.js & React.js
Tags: reacttutorial, node, pos, react
Published: 2018-10-15 23:00:14

---
title: Building simple Point of Sale system with Node.js & React.js
published: true
tags: React tutorial,nodejs,pos,react
canonical_url: https://reactninja.io/2018/07/09/building-simple-point-of-sale-system-with-node-js-react-js/
---

<header>
<div>
<div></div>
</div>
</header>
<section>
<div>
<div>
<h1 id="5597"></h1>
</div>
<div>
<p id="d001" data-scroll="native">
</p>
<div>
<div></div>
<div data-image-id="1*Stdu1qSeLpGv_oKI7lDtBA.png" data-width="1024" data-height="768" data-action="zoom" data-action-value="1*Stdu1qSeLpGv_oKI7lDtBA.png" data-scroll="native"></div>
</div>

</div>
<div>
<p id="ff6b">Building real time applications can be exciting, the idea that pages can be updated without reloading has always been of interest to me.<br>
For the this tutorial we will be creating a real-time point of sale system using node.js and react.js</p>
<p id="ee71"><a href="https://github.com/krissnawat/simple-pos-in-node" target="_blank" rel="noopener" data-href="https://github.com/krissnawat/simple-pos-in-node">Get the source code</a> and see <a href="http://mysterious-plateau-79413.herokuapp.com/" target="_blank" rel="noopener" data-href="http://mysterious-plateau-79413.herokuapp.com">demo</a> here</p>
<p id="c369">This tutorial will comprise of three parts:</p>
<p id="072c"><strong>Part 1 (BackEnd)</strong></p>
<ol>
<li id="c096">Frameworks description</li>
<li id="8d6e">Building the Node app from scratch</li>
<li id="6ec6">Testing with Postman</li>
</ol>
<p id="4d3d"><strong>Part 2 (FrontEnd)</strong><br>
1.Creating a Template React app.<br>
2.Creating Routes and Views with Code Description.</p>
<p id="e3fd">I recommend using the <a href="https://code.visualstudio.com/download" target="_blank" rel="noopener" data-href="https://code.visualstudio.com/download">Vscode Editor</a> for this tutorial.</p>
<p id="28c9"><strong>Frameworks Description and Installation</strong></p>
<p id="d94d">Below are the libraries and frameworks we will be using:</p>
<p id="db51"><a href="https://github.com/louischatriot/nedb" target="_blank" rel="noopener" data-href="https://github.com/louischatriot/nedb"><strong>nedb</strong></a>: NeDB is much like SQLite in that it is a smaller, embeddable version of a much larger database system.NeDB is a smaller NoSQL datastore that mimics MongoDB.</p>
<p id="69d4"><a href="https://socket.io/" target="_blank" rel="noopener" data-href="https://socket.io/"><strong>socket.io</strong></a>:Socket.IO enables real-time bidirectional event-based communication.It works on every platform, browser or device, focusing equally on reliability and speed.<br>
<a href="https://expressjs.com/" target="_blank" rel="noopener" data-href="https://expressjs.com/"><strong>express</strong></a>: Express is a Fast, unopinionated, minimalist web framework for Node.js. express features will enable us to create our web server.<br>
<strong>async</strong><br>
<a href="https://nodemon.io/" target="_blank" rel="noopener" data-href="https://nodemon.io/"><strong>nodemon</strong></a>: Nodemon checks for changes in your source and automatically restart your server.<br>
<strong>body-parser</strong>: body-parser extract the entire body portion of an incoming request stream and exposes it on req.body .<br>
<strong>http</strong>: Http allows Node.js to transfer data over<span data-creator-ids="50199e318f88"> </span>the Hyper Text Transfer Protocol (HTTP).</p>
<p id="2066">Let’s continue by creating the backend with node.js, I will assume you have <a href="https://nodejs.org/en/download/" target="_blank" rel="noopener" data-href="https://nodejs.org/en/download/">node and npm installed</a>.</p>
<p id="ea0d"> **Building the Node app from scratch** </p>
<p id="564a">For this tutorial we are going to create the Node app (express app) from scratch. it can also be done automatically using the <a href="http://www.embeddedjs.com/" target="_blank" rel="noopener" data-href="http://www.embeddedjs.com/">ejs template</a>.</p>
<p id="d9ac">Create a directory via your Command Line Interface (CLI) named <code>real-time-pos-system</code></p>
<p id="df91"><code>mkdir real-rime-pos-system</code></p>
<p id="feff">Access the folder via CLI thus:</p>
<p id="e722"><code>cd real-time-pos-system</code></p>
<p id="34a8">Inside your <code>real-time-pos-system</code> folder create new folder named <code>server</code>from CLI</p>
<p id="bdc3"><code>mkdir server</code></p>
<p id="1757">Let’s install our dependencies:</p>
<p id="94d2"><code>npm init</code></p>
<p id="45d9">Press <code>enter</code> button for the following asked questions:</p>
<pre id="9bf0"><code>package name: (server) Press Enter
version: (1.0.0) Press Enter
description: Node.js app that connect the react-pos app to the Database 
entry point:(index.js) Press Enter
test command: Press Enter
git repository: Press Enter
keywords: Press Enter
author: Enter Your Name
license: (ISC) MIT</code></pre>
<p id="5ba1">you will be shown the following message:</p>
<pre id="bef9"><code>{
    "name": "server"
    version: "1.0.0"
    "description": "Node.js app that connect the react-pos app to the Database 
    "main" : "index.js",
    "scripts": {
       test": "echo \"Error: no test specified\ specified\" &amp;&amp; exit 1"
},
"author": "Your Name",
"license": "MIT"
}</code></pre>
<pre id="bf2b"><code>Is this ok?(yes) yes</code></pre>
<p id="fbca"><strong>Install the following dependencies</strong>:</p>
<p id="bbbf"><code>npm install express --save</code></p>
<p id="8904"><code>npm install http --save</code></p>
<p id="8bc5"><code>npm install nodemon --save</code></p>
<p id="2b83"><code>npm install nedb --save</code></p>
<p id="9fed">Create a file named <code>index.js</code> in your <code>real-time-pos-system</code> folder using your Editor.</p>
<p id="8b48"><code>index.js</code> is the entry point for our node app, as you can see it is located in the root of our app.</p>
<p id="2279">insert the following code in your <code>index.js</code> file</p>
<pre id="c2d6"><code>var express = require("express"),
  http = require("http"),
  port = 80,
  app = require("express")(),
  server = http.createServer(app),
  bodyParser = require("body-parser"),
  io = require("socket.io")(server),
  liveCart;</code></pre>
<pre id="d79c"><code>console.log("Real time POS running");
console.log("Server started");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));</code></pre>
<pre id="aa70"><code>app.all("/*", function(req, res, next) {
  // CORS headers
  res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  // Set custom headers for CORS
  res.header(
    "Access-Control-Allow-Headers",
    "Content-type,Accept,X-Access-Token,X-Key"
  );
  if (req.method == "OPTIONS") {
    res.status(200).end();
  } else {
    next();
  }
});</code></pre>
<pre id="8605"><code>app.get("/", function(req, res) {
  res.send(" Real time POS web app running.");
});</code></pre>
<pre id="32a0"><code>app.use("/api/inventory", require("./api/inventory"));
app.use("/api", require("./api/transactions"));</code></pre>
<pre id="7c39"><code>// Websocket logic for Live Cart
io.on("connection", function(socket) {
  socket.on("cart-transaction-complete", function() {
    socket.broadcast.emit("update-live-cart-display", {});
  });</code></pre>
<pre id="3b8a"><code> // on page load, show user current cart
  socket.on("live-cart-page-loaded", function() {
    socket.emit("update-live-cart-display", liveCart);
  });</code></pre>
<pre id="09a7"><code> // when client connected, make client update live cart
  socket.emit("update-live-cart-display", liveCart);</code></pre>
<pre id="6e10"><code> // when the cart data is updated by the POS
  socket.on("update-live-cart", function(cartData) {
    // keep track of it
    liveCart = cartData;</code></pre>
<pre id="9535"><code> // broadcast updated live cart to all websocket clients
    socket.broadcast.emit("update-live-cart-display", liveCart);
  });
});</code></pre>
<pre id="da1f"><code>server.listen(port, () =&gt; console.log(`Listening on port ${port}`));</code></pre>
<p id="bc67"><strong>index.js Explained</strong></p>
<p id="ad49">This file is the entry point to our node express app. it is comprised of routes that will handle requests and responses to and from the browser.</p>
<p id="a398">Below are dependencies assigned to variables.</p>
<pre id="c563"><code>var express = require("express"),
  http = require("http"),
  port = 80,
  app = require("express")(),
  server = http.createServer(app),
  bodyParser = require("body-parser"),
  io = require("socket.io")(server),
  liveCart</code></pre>
<p id="0ea2">Below, The express variable <code>app</code> is used to allows data to be sent to the database using http request body.</p>
<pre id="090a"><code>app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))</code></pre>
<p id="e3c3">Below are imported files that will represent inventory and transaction routes.</p>
<p id="80e1"><code>app.use("/api/inventory", require("./api/inventory"))</code></p>
<p id="06b1"><code>app.use("/api/transactions", require("./api/transactions"))</code></p>
<p id="d666">Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. — Wikipedia</p>
<p id="6936">Below, the node app is restricted to resources within using CORS and allows specified methods <code>GET</code> <code>PUT</code> <code>POST</code> <code>DELETE</code> and <code>OPTIONS</code> to be used.</p>
<pre id="0974"><code>app.all("/*", function(req, res, next) {
  // CORS headers
  res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required </code><span data-creator-ids="7579144b617e"><code>domain</code></span><code>
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  // Set custom headers for CORS
  res.header(
    "Access-Control-Allow-Headers",
    "Content-type,Accept,X-Access-Token,X-Key"
  );
  if (req.method == "OPTIONS") {
    res.status(200).end();
  } else {
    next();
  }
});</code></pre>
<p id="1c54">Below is the Node app default route</p>
<pre id="d2c9"><code>app.get("/", function(req, res) {
  res.send(" Real time POS web app running.");
});</code></pre>
<p id="2798">The Websocket logic for Live Cart</p>
<pre id="5e21"><code>io.on("connection", function(socket) {
  socket.on("cart-transaction-complete", function() {
    socket.broadcast.emit("update-live-cart-display", {});
  });</code></pre>
<p id="92ef">On page load, give user current cart</p>
<pre id="e0ac"><code>socket.on("live-cart-page-loaded", function() {
    socket.emit("update-live-cart-display", liveCart);
  });</code></pre>
<p id="efeb">On page load, make client update live cart</p>
<pre id="6d79"><code>socket.emit("update-live-cart-display", liveCart)</code></pre>
<p id="f9a7">When the cart data is updated by the POS and keeps track of it</p>
<pre id="24d5"><code>socket.on("update-live-cart", function(cartData) {
    liveCart = cartData;</code></pre>
<p id="4ae3">Broadcasts updated live cart to all websocket clients</p>
<pre id="22ab"><code>socket.broadcast.emit("update-live-cart-display", liveCart);
 });</code></pre>
<p id="5b9a">Let’s continue, create a directory inside <code>server</code> directory:</p>
<p id="658d"><code>mkdir api</code></p>
<p id="3140">Create two files named <code>inventory.js</code> and <code>transactions.js</code> in your api folder</p>
<p id="83aa">insert the following code to your <code>inventory.js</code>:</p>
<pre id="a41c"><code>var app = require("express")();
var server = require("http").Server(app);
var bodyParser = require("body-parser");
var Datastore = require("nedb");
var async = require("async");</code></pre>
<pre id="d7be"><code>app.use(bodyParser.json());</code></pre>
<pre id="4c07"><code>module.exports = app;</code></pre>
<pre id="4880"><code>// Creates Database
var inventoryDB = new Datastore({
  filename: "./server/databases/inventory.db",
  autoload: true
});</code></pre>
<pre id="744f"><code>// GET inventory
app.get("/", function(req, res) {
  res.send("Inventory API");
});</code></pre>
<pre id="7057"><code>// GET a product from inventory by _id
app.get("/product/:productId", function(req, res) {
  if (!req.params.productId) {
    res.status(500).send("ID field is required.");
  } else {
    inventoryDB.findOne({ _id: req.params.productId }, function(err, product) {
      res.send(product);
    });
  }
});</code></pre>
<pre id="4746"><code>// GET all inventory products
app.get("/products", function(req, res) {
  inventoryDB.find({}, function(err, docs) {
    console.log("sending inventory products");
    res.send(docs);
  });
});</code></pre>
<pre id="3dc3"><code>// Create inventory product
app.post("/product", function(req, res) {
  var newProduct = req.body;</code></pre>
<pre id="3ce2"><code> inventoryDB.insert(newProduct, function(err, product) {
    if (err) res.status(500).send(err);
    else res.send(product);
  });
});</code></pre>
<pre id="1d29"><code>app.delete("/product/:productId", function(req, res) {
  inventoryDB.remove({ _id: req.params.productId }, function(err, numRemoved) {
    if (err) res.status(500).send(err);
    else res.sendStatus(200);
  });
});</code></pre>
<pre id="1c04"><code>// Updates inventory product
app.put("/product", function(req, res) {
  var productId = req.body._id;</code></pre>
<pre id="d0f0"><code> inventoryDB.update({ _id: productId }, req.body, {}, function(
    err,
    numReplaced,
    product
  ) {
    if (err) res.status(500).send(err);
    else res.sendStatus(200);
  });
});</code></pre>
<pre id="2dac"><code>app.decrementInventory = function(products) {
  async.eachSeries(products, function(transactionProduct, callback) {
    inventoryDB.findOne({ _id: transactionProduct._id }, function(
      err,
      product
    ) {
      // catch manually added items (don't exist in inventory)
      if (!product || !product.quantity_on_hand) {
        callback();
      } else {
        var updatedQuantity =
          parseInt(product.quantity_on_hand) -
          parseInt(transactionProduct.quantity);</code></pre>
<pre id="5ea7"><code> inventoryDB.update(
          { _id: product._id },
          { $set: { quantity_on_hand: updatedQuantity } },
          {},
          callback
        );
      }
    });
  });
};</code></pre>
<p id="036e"><strong>inventory.js Explained</strong><br>
The necessary dependencies are assigned to variables <code>app</code>, <code>server</code>, <code>bodyParser</code> and <code>Datastore</code>. The <code>app.use(bodyParser.json())</code> will allow the body of a http request to sent to the database.</p>
<p id="12d2">An inventory variable <code>inventoryDB</code> is assigned with an instance of<br>
<strong>nedb</strong> variable <code>Datastore</code> we created earlier. The <code>DataStore</code><br>
instance has two options <code>filename</code> which specifies the path of the database and autoload, which autumatically loads the database if set to true.</p>
<p id="c63d">The <code>app.get("/, function(req, res)</code> function is the default path for the inventory database.</p>
<p id="3b50">The <code>app.get("/product/:/productId</code> function enables the app to get a product from the inventory database using it’s ID.</p>
<p id="4531">The <code>app.get("/products", function(req, res)</code> function gets all products from the inventory database.</p>
<p id="facb">The <code>app.post("/product", function(req, res)</code> function is used to save an inventory product to the database.</p>
<p id="c943">The <code>app.delete("/product/:productId", function(req, res)</code> is used to delete product using product ID.</p>
<p id="3453">The <code>app.put("/product", function(req, res)</code> updates a product using it product ID.</p>
<p id="5b8b">Let’s continue, insert the following code to your <code>transaction.js</code> file:</p>
<pre id="1628"><code>var app = require('express')()
var server = require('http').Server(app)
var bodyParser = require('body-parser')
var Datastore = require('nedb')</code></pre>
<pre id="bd9d"><code>var Inventory = require('./inventory')</code></pre>
<pre id="43ea"><code>app.use(bodyParser.json())</code></pre>
<pre id="7112"><code>module.exports = app</code></pre>
<pre id="bd29"><code>// Create Database
var Transactions = new Datastore({ 
	filename: './server/databases/transactions.db', 
	autoload: true 
})</code></pre>
<pre id="32bf"><code>app.get('/', function (req, res) {
	res.send('Transactions API')
})</code></pre>
<pre id="c4eb"><code>// GET all transactions
app.get('/all', function (req, res) {</code></pre>
<pre id="d683"><code>	Transactions.find({}, function (err, docs) {
		res.send(docs)
	})
})</code></pre>
<pre id="d182"><code>// GET all transactions
app.get('/limit', function (req, res) {</code></pre>
<pre id="39db"><code>	var limit = parseInt(req.query.limit, 10)
	if (!limit) limit = 5</code></pre>
<pre id="27a9"><code>	Transactions.find({}).limit(limit).sort({ date: -1 }).exec(function (err, docs) {
	  res.send(docs)
	})
})</code></pre>
<pre id="c8d9"><code>// GET total sales for the current day
app.get('/day-total', function (req, res) {</code></pre>
<pre id="4df5"><code>	// if date is provided
	if (req.query.date) {
		startDate = new Date(req.query.date)
		startDate.setHours(0,0,0,0)</code></pre>
<pre id="5296"><code> endDate = new Date(req.query.date)
		endDate.setHours(23,59,59,999)
	}
	else {</code></pre>
<pre id="e876"><code> // beginning of current day
		var startDate = new Date()
		startDate.setHours(0,0,0,0)</code></pre>
<pre id="1300"><code> // end of current day
		var endDate = new Date()
		endDate.setHours(23,59,59,999)	
	}

</code></pre>
<pre id="7655"><code>	Transactions.find({ date: { $gte: startDate.toJSON(), $lte: endDate.toJSON() } }, function (err, docs) {
		
		var result = {
			date: startDate
		}</code></pre>
<pre id="404a"><code> if (docs) {</code></pre>
<pre id="55a6"><code> var total = docs.reduce(function (p, c) {
				return p + c.total
			}, 0.00)</code></pre>
<pre id="d0e1"><code> result.total = parseFloat(parseFloat(total).toFixed(2))</code></pre>
<pre id="1bea"><code> res.send(result)
		}
		else {
			result.total = 0
			res.send(result)
		}
	})	
})</code></pre>
<pre id="10e4"><code>// GET transactions for a particular date
app.get('/by-date', function (req, res) {
	
	var startDate = new Date(2018, 2, 21)
	startDate.setHours(0,0,0,0)</code></pre>
<pre id="73ce"><code>	var endDate = new Date(2015, 2, 21)
	endDate.setHours(23,59,59,999)</code></pre>
<pre id="65ec"><code>	Transactions.find({ date: { $gte: startDate.toJSON(), $lte: endDate.toJSON() } }, function (err, docs) {
		if (docs)
			res.send(docs)
	})
})</code></pre>
<pre id="4369"><code>// Add new transaction
app.post('/new', function (req, res) {</code></pre>
<pre id="7433"><code>	var newTransaction = req.body
	
	Transactions.insert(newTransaction, function (err, transaction) {
		if (err) 
			res.status(500).send(err)
		else {
			res.sendStatus(200)
			Inventory.decrementInventory(transaction.products)
		} 
	})
})</code></pre>
<pre id="0376"><code>// GET a single transaction
app.get('/:transactionId', function (req, res) {</code></pre>
<pre id="dbc6"><code>	Transactions.find({ _id: req.params.transactionId }, function (err, doc) {
		if (doc)
			res.send(doc[0])
	})
})</code></pre>
<p id="d16b"><strong>transaction.js Explained</strong><br>
The necessary dependencies are assigned to variables as was done previously.</p>
<p id="d5e3">A Transaction’s variable is created with filename and autoload using the <strong>nedb</strong>variable <code>Datastore</code> as done earlier.</p>
<p id="938d">The <code>app.get("/, function(req, res)</code> function is the default path for the <code>transactions</code> database.</p>
<p id="ebd0">The <code>app.get('/all', function (req, res)</code> function retrieves all transactions from the transactions database.</p>
<p id="8cbc">The <code>app.get('/limit', function (req, res)</code> function retrieves transactions with specified limit.</p>
<p id="11e9">The <code>app.get('/day-total', function (req, res)</code> function is gets total sales for the current day.</p>
<p id="94b5">The <code>app.get('/by-date', function (req, res)</code> function is used to get transactions using a particular date</p>
<p id="9678">The <code>app.post('/new', function (req, res))</code> function is used to add new a transaction</p>
<p id="f0cd">The <code>app.get('/:transactionId', function (req, res)</code> function is used to retrieve a single transaction.</p>
<p id="c9a2"><strong>To Start Node app from root directory using CLI , type command</strong>:</p>
<p id="67a4"><code>nodemon index.js</code></p>
<p id="c094">end in backend section</p>
<h3 id="2c9d">Frontend part</h3>
<p id="1da3">We are going to accomplish the following:</p>
<p id="bd20">1.Creating a Template React app.<br>
2.Creating Routes and Views with Code Description.</p>
<p id="a882">See<a href="https://github.com/kels-orien/real-time-pos-system" target="_blank" rel="noopener" data-href="https://github.com/kels-orien/real-time-pos-system"> here</a> for source code<br>
Frameworks we will be using:</p>
<p id="e31a"><strong>axios</strong> is a Promise based HTTP client for the browser and node.js.</p>
<p id="d3f6"><strong>Bootstrap</strong> is a free open source library that contains HTML and CSS design templates for designing websites and web applications.</p>
<p id="fb8c"><strong>React-Bootstrap</strong> is a Bootstrap 3 components built with React.</p>
<p id="960d"><strong>moment</strong> is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.</p>
<p id="9d67"><strong>React</strong> is a JavaScript library for building user interfaces.</p>
<p id="7094"><strong>Creating a Template React App</strong></p>
<p id="e7f9">Make sure you have <a href="https://nodejs.org/en/download/" target="_blank" rel="noopener" data-href="https://nodejs.org/en/download/">Node and NPM</a> installed.</p>
<p id="e877">Check Node and Npm Version via Command Line Interface (CLI)</p>
<p id="680e"><code>node -v</code></p>
<p id="b883"><code>npm -v</code></p>
<p id="7f64">Access the <code>real-time-pos-folder</code> we used in part 1 Using CLI to create react app globally using npm:</p>
<p id="9b1f">For npm version 5.1 or earlier<br>
<code>npm install -g create-react-app</code></p>
<p id="5566">To create your app, run a single command<br>
npm install create-react-app react-pos</p>
<p id="7a1d">For npm version 5.2+ and higher<br>
<code>npx install -g create-react-app</code></p>
<p id="1e8c">To create our appointment scheduler app, run a single command<br>
<code>npx install create-react-app react-pos</code></p>
<p id="9304">The Directory of your app will look something like this:</p>
<p id="ea79">react-pos<br>
<code>├── README.md</code><br>
<code>├── node_modules</code><br>
<code>├── package.json</code><br>
<code>├── .gitignore</code><br>
<code>├── public</code><br>
<code>│ └── favicon.ico</code><br>
<code>│ └── index.html</code><br>
<code>│ └── manifest.json</code><br>
<code>└── src</code><br>
<code>└── App.css</code><br>
<code>└── App.js</code><br>
<code>└── App.test.js</code><br>
<code>└── index.css</code><br>
<code>└── index.js</code><br>
<code>└── logo.svg</code><br>
<code>└── registerServiceWorker.js</code></p>
<p id="8842">To start the project in development mode via CLI<br>
<code>npm start</code></p>
<p id="50e1">Access your app directory using:<br>
<code>cd react-pos</code></p>
<p id="8898">Install the following dependencies:<br>
<code>npm install bootstrap</code></p>
<p id="fc6c"><code>npm install react-bootstrap</code></p>
<p id="1ab5"><code>npm install axios</code></p>
<p id="bda8"><code>npm install moment</code></p>
<p id="f42e"><strong>Creating Routes and Views</strong></p>
<p id="62f8">We are going to start by creating our routes</p>
<p id="2765">Start by editing your <code>App.js</code> in your root directory with following code:</p>
<pre id="890e"><code>import React from "react";
import Header from "./js/components/Header";
import Main from "./js/components/Main";</code></pre>
<pre id="b72d"><code>const App = () =&gt; (
  &lt;div&gt;
    &lt;Main /&gt;
  &lt;/div&gt;
);</code></pre>
<pre id="101b"><code>export default App;</code></pre>
<p id="d59c">Also update your <code>index.js</code> in your root directory:</p>
<pre id="265f"><code>import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import registerServiceWorker from "./registerServiceWorker";
import "./index.css";
import "bootstrap/dist/css/bootstrap.css";
import { makeRoutes } from "./routes";
import App from "./App";</code></pre>
<pre id="60ad"><code>render(
  &lt;BrowserRouter&gt;
    &lt;App /&gt;
  &lt;/BrowserRouter&gt;,
  document.getElementById("root")
);
registerServiceWorker();</code></pre>
<p id="53dc">You maybe wondering about the <code>Main</code> and <code>Header</code> Components, but we will create them shortly:</p>
<p id="1c0a">Create the following path in your “src” folder directory of your react-pos app:</p>
<p id="059c"><code>js/components</code></p>
<p id="e05b">Create Main.js in the <code>js/components</code> folder with the following code:</p>
<pre id="0574"><code>import React from "react";
import { Switch, Route } from "react-router-dom";
import Inventory from "./Inventory";
import Pos from "./Pos";
import Transactions from "./Transactions";
import LiveCart from "./LiveCart";</code></pre>
<pre id="e90a"><code>const Main = () =&gt; (
  &lt;main&gt;
    &lt;Switch&gt;
      &lt;Route exact path="/" component={Pos} /&gt;
      &lt;Route path="/inventory" component={Inventory} /&gt;
      &lt;Route path="/transactions" component={Transactions} /&gt;
      &lt;Route path="/livecart" component={LiveCart} /&gt;
    &lt;/Switch&gt;
  &lt;/main&gt;
);</code></pre>
<pre id="5e33"><code>export default Main;</code></pre>
<p id="bb47">Notice that our <code>Main.js</code> component is not a class; rather it is a functional component,. Arrow function to be precise. we are creating our routes using functions.</p>
<p id="5153">Lets create our <code>Header.js</code> component for navigation of our app</p>
<pre id="caf6"><code>import React from "react";
import { Link } from "react-router-dom";</code></pre>
<pre id="df82"><code>// The Header creates links that can be used to navigate
// between routes.
const Header = () =&gt; (
  &lt;div className="text-center"&gt;
    &lt;h1&gt;
      &lt;a href="/#/"&gt;Real Time Point POS&lt;/a&gt;
    &lt;/h1&gt;</code></pre>
<pre id="7dcb"><code> &lt;ul className="nav-menu"&gt;
      &lt;li className="lead"&gt;
        &lt;Link to="/inventory"&gt;Inventory&lt;/Link&gt;
      &lt;/li&gt;
      &lt;li className="lead"&gt;
        &lt;Link to="/"&gt;POS&lt;/Link&gt;
      &lt;/li&gt;
      &lt;li className="lead"&gt;
        &lt;Link to="/transactions"&gt;Transactions&lt;/Link&gt;
      &lt;/li&gt;
      &lt;li className="lead"&gt;
        &lt;Link to="/livecart"&gt;LiveCart&lt;/Link&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
);</code></pre>
<pre id="9cc4"><code>export default Header;</code></pre>
<p id="bc99">you will notice as we continue that the <code>Header</code> component is included in all parent components.</p>
<p id="37cb">Now lets create our views, Let’s start with the <code>Inventory.js</code> component in the <code>src/js/component/</code> folder.</p>
<pre id="74ee"><code>import React, { Component } from "react";
import "./App.css";
import Header from "./Header";
import Product from "./Product";
import axios from "axios";</code></pre>
<pre id="de69"><code>const HOST = "<a href="http://localhost/" target="_blank" rel="nofollow noopener" data-href="http://localhost/">http://localhost:80</a>";</code></pre>
<pre id="6bc1"><code>class Inventory extends Component {
  constructor(props) {
    super(props);</code></pre>
<pre id="af7f"><code> this.state = { products: [] };
  }
  componentWillMount() {
    var url = HOST + `/api/inventory/products`;
    axios.get(url).then(response =&gt; {
      this.setState({ products: response.data });
    });
  }
  render() {
    var { products } = this.state;</code></pre>
<pre id="005e"><code> var renderProducts = () =&gt; {
      if (products.length === 0) {
        return &lt;p&gt;{products}&lt;/p&gt;;
      }
      return products.map(product =&gt; &lt;Product {...product} /&gt;);
    };</code></pre>
<pre id="092f"><code> return (
      &lt;div&gt;
        &lt;Header /&gt;</code></pre>
<pre id="3c22"><code> &lt;div class="container"&gt;
          &lt;a
            href="#/inventory/create-product"
            class="btn btn-success pull-right"
          &gt;
            &lt;i class="glyphicon glyphicon-plus" /&gt; Add New Item
          &lt;/a&gt;
          &lt;br /&gt;
          &lt;br /&gt;</code></pre>
<pre id="1bd9"><code> &lt;table class="table"&gt;
            &lt;thead&gt;
              &lt;tr&gt;
                &lt;th scope="col"&gt;Name&lt;/th&gt;
                &lt;th scope="col"&gt;Price&lt;/th&gt;
                &lt;th scope="col"&gt;Quantity on Hand&lt;/th&gt;
                &lt;th /&gt;
              &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;{renderProducts()}&lt;/tbody&gt;
          &lt;/table&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
}</code></pre>
<pre id="ca57"><code>export default Inventory;</code></pre>
<p id="d9dc">Notice that We are using a class for the <code>inventory</code> component above. <code>componentWillMount</code> is a Lifecycle method which is used to modify the component state, in this particular situation we are retrieving products from the inventory database by through our Node.js Express App We created in part 1. the response is assigned to the product array using <code>setState</code> . All this is done before the page is fully loaded.</p>
<p id="5d0b">The <code>render</code> function will display our UI elements in the DOM (Document Object Model). The <code>renderFunction</code> checks the product array and display the result in the DOM.</p>
<p id="abdd">Let’s move on to the <code>POS.js</code> Component. The <code>Pos</code> component will allows the user to add items to cart with prices. the cart will be updated in real time.</p>
<p id="c3e0">Create a <code>Pos.js</code> file in <code>src/js/component/</code> folder:</p>
<pre id="1237"><code>import React, { Component } from "react";
import "./App.css";
import Header from "./Header";
import io from "socket.io-client";
import axios from "axios";
import moment from "moment";
import { Modal, Button } from "react-bootstrap";
import LivePos from "./LivePos";</code></pre>
<pre id="df81"><code>const HOST = "<a href="http://localhost/" target="_blank" rel="nofollow noopener" data-href="http://localhost/">http://localhost:80</a>";
let socket = io.connect(HOST);</code></pre>
<pre id="14ce"><code>class Pos extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      quantity: 1,
      id: 0,
      open: true,
      close: false,
      addItemModal: false,
      checkOutModal: false,
      amountDueModal: false,
      totalPayment: 0,
      total: 0,
      changeDue: 0,
      name: "",
      price: 0
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleName = this.handleName.bind(this);
    this.handlePrice = this.handlePrice.bind(this);
    this.handlePayment = this.handlePayment.bind(this);
    this.handleQuantityChange = this.handleQuantityChange.bind(this);
    this.handleCheckOut = this.handleCheckOut.bind(this);
  }
  componentDidUpdate() {
    if (this.state.items.length !== 0) {
      socket.emit("update-live-cart", this.state.items);
    }
  }
  handleSubmit = e =&gt; {
    e.preventDefault();
    this.setState({ addItemModal: false });</code></pre>
<pre id="41d8"><code> const currentItem = {
      id: this.state.id++,
      name: this.state.name,
      price: this.state.price,
      quantity: this.state.quantity
    };
    var items = this.state.items;
    items.push(currentItem);
    this.setState({ items: items });
  };
  handleName = e =&gt; {
    this.setState({ name: e.target.value });
  };
  handlePrice = e =&gt; {
    this.setState({ price: e.target.value });
  };
  handlePayment = () =&gt; {
    this.setState({ checkOutModal: false });
    var amountDiff =
      parseInt(this.state.total, 10) - parseInt(this.state.totalPayment, 10);
    if (this.state.total &lt;= this.state.totalPayment) {
      this.setState({ changeDue: amountDiff });
      this.setState({ receiptModal: true });
      this.handleSaveToDB();
      this.setState({ items: [] });
      this.setState({ total: 0 });
    } else {
      this.setState({ changeDue: amountDiff });
      this.setState({ amountDueModal: true });
    }
  };
  handleQuantityChange = (id, quantity) =&gt; {
    var items = this.state.items;
    for (var i = 0; i &lt; items.length; i++) {
      if (items[i].id === id) {
        items[i].quantity = quantity;
        this.setState({ items: items });
      }
    }
  };
  handleCheckOut = () =&gt; {
    this.setState({ checkOutModal: true });
    var items = this.state.items;
    var totalCost = 0;
    for (var i = 0; i &lt; items.length; i++) {
      var price = items[i].price * items[i].quantity;
      totalCost = parseInt(totalCost, 10) + parseInt(price, 10);
    }
    this.setState({ total: totalCost });
  };
  handleSaveToDB = () =&gt; {
    const transaction = {
      date: moment().format("DD-MMM-YYYY HH:mm:ss"),
      total: this.state.total,
      items: this.state.items
    };
    axios.post(HOST + "/api/new", transaction).catch(err =&gt; {
      console.log(err);
    });
  };
  render() {
    var { quantity, modal, items } = this.state;</code></pre>
<pre id="ca55"><code> var renderAmountDue = () =&gt; {
      return (
        &lt;Modal show={this.state.amountDueModal}&gt;
          &lt;Modal.Header closeButton&gt;
            &lt;Modal.Title&gt;Amount&lt;/Modal.Title&gt;
          &lt;/Modal.Header&gt;
          &lt;Modal.Body&gt;
            &lt;h3&gt;
              Amount Due:
              &lt;span class="text-danger"&gt;{this.state.changeDue}&lt;/span&gt;
            &lt;/h3&gt;
            &lt;p&gt;Customer payment incomplete; Correct and Try again&lt;/p&gt;
          &lt;/Modal.Body&gt;
          &lt;Modal.Footer&gt;
            &lt;Button onClick={() =&gt; this.setState({ amountDueModal: false })}&gt;
              close
            &lt;/Button&gt;
          &lt;/Modal.Footer&gt;
        &lt;/Modal&gt;
      );
    };
    var renderReceipt = () =&gt; {
      return (
        &lt;Modal show={this.state.receiptModal}&gt;
          &lt;Modal.Header closeButton&gt;
            &lt;Modal.Title&gt;Receipt&lt;/Modal.Title&gt;
          &lt;/Modal.Header&gt;
          &lt;Modal.Body&gt;
            &lt;h3&gt;
              Total:
              &lt;span class="text-danger"&gt;{this.state.totalPayment}&lt;/span&gt;
            &lt;/h3&gt;
            &lt;h3&gt;
              Change Due:
              &lt;span class="text-success"&gt;{this.state.changeDue}&lt;/span&gt;
            &lt;/h3&gt;
          &lt;/Modal.Body&gt;
          &lt;Modal.Footer&gt;
            &lt;Button onClick={() =&gt; this.setState({ receiptModal: false })}&gt;
              close
            &lt;/Button&gt;
          &lt;/Modal.Footer&gt;
        &lt;/Modal&gt;
      );
    };</code></pre>
<pre id="0aaa"><code> var renderLivePos = () =&gt; {
      if (items.length === 0) {
        return &lt;p&gt; No products added&lt;/p&gt;;
      } else {
        return items.map(
          item =&gt; (
            &lt;LivePos {...item} onQuantityChange={this.handleQuantityChange} /&gt;
          ),
          this
        );
      }
    };</code></pre>
<pre id="c9d3"><code> return (
      &lt;div&gt;
        &lt;Header /&gt;
        &lt;div class="container"&gt;
          &lt;div class="text-center"&gt;
            &lt;span class="lead"&gt;Total&lt;/span&gt;
            &lt;br /&gt;
            &lt;span class="text-success checkout-total-price"&gt;
              ${this.state.total}
              &lt;span /&gt;
            &lt;/span&gt;
            &lt;div&gt;
              &lt;button
                class="btn btn-success lead"
                id="checkoutButton"
                onClick={this.handleCheckOut}
              &gt;
                &lt;i class="glyphicon glyphicon-shopping-cart" /&gt;
                &lt;br /&gt;
                &lt;br /&gt;
                C&lt;br /&gt;
                h&lt;br /&gt;
                e&lt;br /&gt;
                c&lt;br /&gt;
                k&lt;br /&gt;
                o&lt;br /&gt;
                u&lt;br /&gt;
                t
              &lt;/button&gt;
              &lt;div className="modal-body"&gt;
                &lt;Modal show={this.state.checkOutModal}&gt;
                  &lt;Modal.Header closeButton&gt;
                    &lt;Modal.Title&gt;Checkout&lt;/Modal.Title&gt;
                  &lt;/Modal.Header&gt;
                  &lt;Modal.Body&gt;
                    &lt;div ng-hide="transactionComplete" class="lead"&gt;
                      &lt;h3&gt;
                        Total:
                        &lt;span class="text-danger"&gt; {this.state.total} &lt;/span&gt;
                      &lt;/h3&gt;</code></pre>
<pre id="4e8f"><code> &lt;form
                        class="form-horizontal"
                        name="checkoutForm"
                        onSubmit={this.handlePayment}
                      &gt;
                        &lt;div class="form-group"&gt;
                          &lt;div class="input-group"&gt;
                            &lt;div class="input-group-addon"&gt;$&lt;/div&gt;
                            &lt;input
                              type="number"
                              id="checkoutPaymentAmount"
                              class="form-control input-lg"
                              name="payment"
                              onChange={event =&gt;
                                this.setState({
                                  totalPayment: event.target.value
                                })
                              }
                              min="0"
                            /&gt;
                          &lt;/div&gt;
                        &lt;/div&gt;</code></pre>
<pre id="15ad"><code> &lt;p class="text-danger"&gt;Enter payment amount.&lt;/p&gt;
                        &lt;div class="lead" /&gt;
                        &lt;Button
                          class="btn btn-primary btn-lg lead"
                          onClick={this.handlePayment}
                        &gt;
                          Print Receipt
                        &lt;/Button&gt;
                      &lt;/form&gt;
                    &lt;/div&gt;
                  &lt;/Modal.Body&gt;
                  &lt;Modal.Footer&gt;
                    &lt;Button
                      onClick={() =&gt; this.setState({ checkOutModal: false })}
                    &gt;
                      Close
                    &lt;/Button&gt;
                  &lt;/Modal.Footer&gt;
                &lt;/Modal&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          {renderAmountDue()}
          {renderReceipt()}
          &lt;table class="pos table table-responsive table-striped table-hover"&gt;
            &lt;thead&gt;
              &lt;tr&gt;
                &lt;td colspan="6" class="text-center"&gt;
                  &lt;span class="pull-left"&gt;
                    &lt;button
                      onClick={() =&gt; this.setState({ addItemModal: true })}
                      class="btn btn-default btn-sm"
                    &gt;
                      &lt;i class="glyphicon glyphicon-plus" /&gt; Add Item
                    &lt;/button&gt;
                  &lt;/span&gt;
                  &lt;Modal show={this.state.addItemModal} onHide={this.close}&gt;
                    &lt;Modal.Header closeButton&gt;
                      &lt;Modal.Title&gt;Add item(Product)&lt;/Modal.Title&gt;
                    &lt;/Modal.Header&gt;
                    &lt;Modal.Body&gt;
                      &lt;form
                        ref="form"
                        onSubmit={this.handleSubmit}
                        class="form-horizontal"
                      &gt;
                        &lt;div class="form-group"&gt;
                          &lt;label class="col-md-2 lead" for="name"&gt;
                            Name
                          &lt;/label&gt;
                          &lt;div class="col-md-8 input-group"&gt;
                            &lt;input
                              class="form-control"
                              name="name"
                              required
                              onChange={this.handleName}
                            /&gt;
                          &lt;/div&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                          &lt;label class="col-md-2 lead" for="price"&gt;
                            Price
                          &lt;/label&gt;
                          &lt;div class="col-md-8 input-group"&gt;
                            &lt;div class="input-group-addon"&gt;$&lt;/div&gt;</code></pre>
<pre id="6eb7"><code> &lt;input
                              type="number"
                              step="any"
                              min="0"
                              onChange={this.handlePrice}
                              class="form-control"
                              name="price"
                              required
                            /&gt;
                          &lt;/div&gt;
                        &lt;/div&gt;</code></pre>
<pre id="1fd0"><code> &lt;p class="text-danger"&gt;Enter price for item.&lt;/p&gt;
                      &lt;/form&gt;
                    &lt;/Modal.Body&gt;
                    &lt;Modal.Footer&gt;
                      &lt;Button onClick={this.handleSubmit}&gt;Add&lt;/Button&gt;
                      &lt;Button
                        onClick={() =&gt; this.setState({ addItemModal: false })}
                      &gt;
                        Cancel
                      &lt;/Button&gt;
                    &lt;/Modal.Footer&gt;
                  &lt;/Modal&gt;
                &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr class="titles"&gt;
                &lt;th&gt;Name&lt;/th&gt;
                &lt;th&gt;Price&lt;/th&gt;
                &lt;th&gt;Quantity&lt;/th&gt;
                &lt;th&gt;Tax&lt;/th&gt;
                &lt;th&gt;Total&lt;/th&gt;
                &lt;th /&gt;
              &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;{renderLivePos()}&lt;/tbody&gt;
          &lt;/table&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
}</code></pre>
<pre id="90b9"><code>export default Pos;</code></pre>
<p id="619e">The <code>Pos</code> component enables the user to add items to cart, accept payment via checkout, print the receipt and saves to the database.</p>
<p id="8334">The <code>componentDidUpdate</code> Lifecycle method is used to check the state of the <code>items</code>array everytime the component has been updated. if the <code>item</code> array contain one or more products the <code>LiveCart</code> is updated in real-time using <code>socket.io</code>.</p>
<p id="0578">The <code>handleSubmit</code> function adds an item to the item array.</p>
<p id="0b3b">The <code>handlePrice</code> function assigns the current price of an item to the price variable using the <code>setState</code></p>
<p id="ad81">The <code>handleName</code> function assigns the current name of an item to the name variable using the <code>setState</code></p>
<p id="a5a9">The <code>handlePayment</code> function checks the amount the customer payment paid for the items against the total cost.</p>
<p id="8a99">The <code>handleQuantityChange</code> function is a prop of the child component <code>LivePos</code>, it updates the quantity of an item when the user increases or reduces it.</p>
<p id="5c0e">The <code>handleCheckout</code> function calculates the total cost of items purchased by the customer and updates <code>total</code> using setState.</p>
<p id="cad6">The <code>renderLivePos</code> function renders an item as it is added to the item array using the child component <code>LivePos</code>.</p>
<p id="37ae">The <code>renderReceipt</code> displays a modal confirming payment.</p>
<p id="b9df">The <code>renderAmountDue</code> display a modal to inform the user of incomplete payment.</p>
<p id="643c">The <code>LivePos</code> is a child component of the <code>Pos</code> component. it display each item as it added to the <code>Pos</code> component. The <code>LivePos</code> is also known as a Presentation component. check the source <a href="https://github.com/kels-orien/real-time-pos-system/blob/master/react-pos/src/js/components/LivePos.js" target="_blank" rel="noopener" data-href="https://github.com/kels-orien/real-time-pos-system/blob/master/react-pos/src/js/components/LivePos.js">code</a> this component</p>
<p id="8821">The <code>handleSaveToDB</code> function saves the transaction to the database</p>
<p id="002c">Let’s proceed to the Livecart component:</p>
<pre id="b444"><code>import React, { Component } from "react";
import "./App.css";
import io from "socket.io-client";
import Header from "./Header";
import axios from "axios";
import RecentTransactions from "./RecentTransactions";
import LiveTransactions from "./</code><span data-creator-ids="ce0f749a401d"><code>LiveTransactions</code></span><code>";
import moment from "moment";</code></pre>
<pre id="4ecc"><code>const HOST = "<a href="http://localhost/" target="_blank" rel="nofollow noopener" data-href="http://localhost/">http://localhost:80</a>";
var url = HOST + `/api//day-total/`;
class LiveCart extends Component {
  constructor(props) {
    super(props);
    this.state = { transactions: [], liveTransactions: [] };
  }
  componentWillMount() {
    // console.dir(socket);
    axios.get(url).then(response =&gt; {
      this.setState({ transactions: response.data });
      console.log("response", response.data);
    });</code></pre>
<pre id="7eeb"><code> var socket = io.connect(HOST);</code></pre>
<pre id="4bff"><code> socket.on("update-live-cart-display", liveCart =&gt; {
      this.setState({ liveTransactions: liveCart });
    });
  }
  componentWillUnmount() {
    // socket.disconnect();
    // alert("Disconnecting Socket as component will unmount");
  }
  render() {
    var { transactions, liveTransactions } = this.state;
    var renderRecentTransactions = () =&gt; {
      if (transactions.length === 0) {
        return &lt;p&gt;No recent transactions available&lt;/p&gt;;
      } else {
        return transactions.map(transaction =&gt; (
          &lt;RecentTransactions {...transaction} /&gt;
        ));
      }
    };
    var renderDate = () =&gt; {
      return moment().format("DD-MMM-YYYY HH:mm:ss");
    };
    var renderLiveTransactions = () =&gt; {
      if (liveTransactions.length === 0) {
        return (
          &lt;div&gt;
            &lt;div class="col-md-5 pull-right"&gt;
              &lt;div&gt;
                &lt;div class="alert alert-warning text-center" role="alert"&gt;
                  &lt;strong&gt;Not Active:&lt;/strong&gt; No items added at the moment.
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        );
      } else {
        return liveTransactions.map(liveTransaction =&gt; (
          &lt;LiveTransactions {...liveTransaction} /&gt;
        ));
      }
    };
    return (
      &lt;div&gt;
        &lt;Header /&gt;
        &lt;div class="livecart"&gt;
          &lt;div class="col-md-5 pull-right"&gt;
            &lt;div class="panel panel-primary"&gt;
              &lt;div class="panel-heading text-center lead"&gt;{renderDate()}&lt;/div&gt;</code></pre>
<pre id="4d33"><code> &lt;table class="receipt table table-hover"&gt;
                &lt;thead&gt;
                  &lt;tr class="small"&gt;
                    &lt;th&gt; Quantity &lt;/th&gt;
                    &lt;th&gt; Product &lt;/th&gt;
                    &lt;th&gt; Price &lt;/th&gt;
                  &lt;/tr&gt;
                &lt;/thead&gt;
                &lt;tbody&gt;{renderLiveTransactions()}&lt;/tbody&gt;
              &lt;/table&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div class="col-md-5 pull-left"&gt;
            &lt;div class="panel panel-default"&gt;
              &lt;div class="panel-heading lead text-center"&gt;
                Recent Transactions
              &lt;/div&gt;</code></pre>
<pre id="eade"><code> &lt;div class="panel-body"&gt;
                &lt;div class="text-center"&gt;
                  &lt;span&gt;Today's Sales&lt;/span&gt;
                  &lt;br /&gt;
                  &lt;span class="text-success checkout-total-price"&gt;
                    $&lt;span /&gt;
                  &lt;/span&gt;
                &lt;/div&gt;</code></pre>
<pre id="30ac"><code> &lt;table class="table table-hover table-striped"&gt;
                  &lt;thead&gt;
                    &lt;tr&gt;
                      &lt;th&gt;Time&lt;/th&gt;
                      &lt;th&gt;Total&lt;/th&gt;
                    &lt;/tr&gt;
                  &lt;/thead&gt;
                  &lt;tbody&gt;{renderRecentTransactions()}&lt;/tbody&gt;
                &lt;/table&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
}</code></pre>
<pre id="09b1"><code>export default LiveCart;</code></pre>
<p id="cc4a">The <code>LiveCart</code> component renders recent and current transactions.</p>
<p id="d399">On <code>Co</code><span data-creator-ids="50199e318f88"><code>m</code></span><code>ponentWillMount</code> recent transactions are retrieved, followed by current items on livecart using <code>socket.io-client</code></p>
<p id="20ca"><code>render</code> function display the user interface to DOM. <code>renderRecentTransactions</code> child<br>
component is used to render recent transactions saved to the Database. <code>renderLiveTransactions</code> is also a child component used to render current transactions. Both <code>renderRecentTransactions</code> and <code>renderLiveTransactions</code>are presentational components.</p>
<p id="eb29">Let’s move on to the Transaction component:</p>
<pre id="e02c"><code>import React, { Component } from "react";
import "./App.css";
import Header from "./Header";
import CompleteTransactions from "./CompleteTransactions";
import axios from "axios";</code></pre>
<pre id="3743"><code>const HOST = "<a href="http://localhost/" target="_blank" rel="nofollow noopener" data-href="http://localhost/">http://localhost:80</a>";
const url = HOST + `/api/all`;</code></pre>
<pre id="dde8"><code>class Transactions extends Component {
  constructor(props) {
    super(props);
    this.state = { transactions: [] };
  }
  componentWillMount() {
    axios.get(url).then(response =&gt; {
      this.setState({ transactions: response.data });
      console.log("response:", response.data);
    });
  }
  render() {
    var { transactions } = this.state;</code></pre>
<pre id="646f"><code> var rendertransactions = () =&gt; {
      if (transactions.length === 0) {
        return &lt;p&gt;No Transactions found&lt;/p&gt;;
      }
      return transactions.map(transaction =&gt; (
        &lt;CompleteTransactions {...transaction} /&gt;
      ));
    };</code></pre>
<pre id="51ca"><code> return (
      &lt;div&gt;
        &lt;Header /&gt;
        &lt;div class="text-center"&gt;
          &lt;span class=""&gt;Today's Sales&lt;/span&gt;
          &lt;br /&gt;
          &lt;span class="text-success checkout-total-price"&gt;
            $ &lt;span /&gt;
          &lt;/span&gt;
        &lt;/div&gt;</code></pre>
<pre id="ad64"><code> &lt;br /&gt;
        &lt;br /&gt;</code></pre>
<pre id="2844"><code> &lt;table class="table table-hover table-striped"&gt;
          &lt;thead&gt;
            &lt;tr&gt;
              &lt;th&gt;Time&lt;/th&gt;
              &lt;th&gt;Total&lt;/th&gt;
              &lt;th&gt;Products&lt;/th&gt;
              &lt;th&gt;Open&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/thead&gt;
          &lt;tbody&gt;{rendertransactions()}&lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;
    );
  }
}</code></pre>
<pre id="4072"><code>export default Transactions;</code></pre>
<p id="1873">On the <code>componentWillMount</code> all transactions and retrieved from the database.</p>
<p id="a0b3">The <code>rendertransactions</code> function displays all the transactions using the <code>CompleteTransactions</code> presentional component. See source code for more on ‘CompleteTransactions.</p>
<p id="dddc">We have succeeded in building The front and Backend of Real time Point of Sale System. I hope you had a blast.</p>
</div>
<div></div>
<div></div>
</div>
</section>
<footer>
<div>
<div></div>
</div>
<div data-action-scope="_actionscope_5">
<div>
<div>
<div>
<div data-action-scope="_actionscope_6">
<div>
<div>
<div>
<div data-post-id="7606859caebd" data-source="responses---------0----------------" data-action-scope="_actionscope_8" data-scroll="native">
<div>
<div>
<section>
<div>
<div>
<p id="1df0">
</p>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</footer>

The post [Building simple Point of Sale system with Node.js & React.js](https://reactninja.io/2018/07/09/building-simple-point-of-sale-system-with-node-js-react-js/) appeared first on [ReactNinja](https://reactninja.io).