Build an E-commerce Website using Gatsby and Cosmic JS

Build an E-commerce Website using Gatsby and Cosmic JS

This tutorial will show you how to build an e-commerce app using Gatsby and Cosmic JS.

This tutorial will show you how to build an e-commerce app using Gatsby and Cosmic JS.

This app will give you a basic idea of how we can integrate an e-commerce app with Cosmic JS to store our data. In this app example, all order data will be stored in the Cosmic JS database and its speed will charm you. Let’s get started.

Check out the demo

Download the codebase

Introduction to the App

Here we are building an e-commerce app in Gatsby with the backend power of Cosmic JS. We will make some navigation based on an e-commerce website and at the end placed order will be saved on the Cosmic JS database. Cosmic JS provides npm module for JavaScript technologies. Also, it provides API endpoints with the help of which you can directly apply CRUD operations on it. Here we are using API endpoints to store our data.

Requirements

  • Node.js must be installed on your system, it is required to run npm commands. Choose its latest version and install it on your system.
  • After node.js, install Gatsby CLI on your system globally. You can find it here: Gatsby CLI

Let’s Get Started

We assumed that you have installed the above software and CLI. Now run the following command to create a new Gatsby app:

gatsby new Gatsby-Ecommerce

After executing this command successfully, it is ensured that you have created a new Gatsby app with the name “Gatsby-Ecommerce”. Now to start this, execute the following command from the terminal:

npm start

It will run your app and opens the port: http://localhost:8000/

Configuration with Cosmic JS

Cosmic JS is two in one service provider that means it gives the facility of database and server as well. So you need to signup for Cosmic JS first and create a new bucket with any name you want, here we created the bucket with the name Gatsby Ecommerce. Now it is time to create an object type, which means to the data management. Create object type named orders, All orders will be stored in this object. Now we have to do some basic setting, for this goto basic setting in your dashboard. Have a look at the below screenshot:

Here you can see the read/write keys fields and other IDs. Click on generate read and write keys and save on any text file along with bucket ID and slug.

Now open your Gatsby project in any IDE, here I’m using Visual Basic Code. Now create a folder named config in root od the project and create a new file with name config.js inside the config folder and save the above IDs and keys in the following format:

const config = {
    bucket_name: process.env.GATSBY_APP_BUCKET_SLUG || "Gatsby Ecommerce",
    bucket_slug: process.env.GATSBY_APP_BUCKET_SLUG || "gatsby-ecommerce",
    bucket_id: process.env.GATSBY_APP_BUCKET_ID || "5cc1ead2516526548dab945e",
    read_key: process.env.GATSBY_APP_BUCKET_READ_KEY || "",
    write_key: process.env.GATSBY_APP_BUCKET_WRITE_KEY || "",
    url: "https://api.cosmicjs.com/v1/"
  }
  export default config;

It is important for you to manage your project properly, so have a look at the screenshot of the folder structure of the project:

Inbuilt Bucket

You can also use an inbuilt bucket. For this, you have to import that inbuilt bucket in your Cosmic JS account. Here we are providing our bucket for you. You just need to follow these steps:

  1. Go to our Git repo and download the bucket.json file
  2. Now go to your Cosmic JS dashboard and click on basic settings
  3. Click on Import/Export and click on Add import file, and import the bucket.json file

Now everything is ready, we can move to implement our app now

Home Page

Now we are going to build our app, and the main page is the home page. On this page, we will show the items for shopping. We will add a few items as this app will only show you the compatibility of Gatsby e-commerce app with Cosmic JS. Location of the home component is src/components/home.js

Check the code of the home component, then we will explain it.

import React, { Component } from 'react';
import Iphone8 from "./iPhones/iphone8"
import Iphonex from "./iPhones/iphonex"
import Iphonexs from "./iPhones/iphonexs"
import "./layout.css";
import { Modal, Button } from 'react-bootstrap';
import { Link } from "gatsby";
import _ from "lodash";

class Home extends Component {
    products = [];
    constructor(props) {
        super(props);
        this.state = {
            iPhone8Show: false,
            iPhoneXShow: false,
            iPhoneXSShow: false,
            alert: "",
        };
        this.handleiPhone8Show = this.handleiPhone8Show.bind(this);
        this.handleiPhone8Close = this.handleiPhone8Close.bind(this);
        this.handleiPhoneXShow = this.handleiPhoneXShow.bind(this);
        this.handleiPhoneXClose = this.handleiPhoneXClose.bind(this);
        this.handleiPhoneXSShow = this.handleiPhoneXSShow.bind(this);
        this.handleiPhoneXSClose = this.handleiPhoneXSClose.bind(this);
    }

    handleiPhone8Close() {
        this.setState({ iPhone8Show: false });
      }
    
      handleiPhone8Show() {
        this.setState({ iPhone8Show: true });
      }
      handleiPhoneXClose() {
        this.setState({ iPhoneXShow: false });
      }
    
      handleiPhoneXShow() {
        this.setState({ iPhoneXShow: true });
      }
      handleiPhoneXSClose() {
        this.setState({ iPhoneXSShow: false });
      }
    
      handleiPhoneXSShow() {
        this.setState({ iPhoneXSShow: true });
      }

    //   Add products to cart
      addToCart = (e)=>
      {
        var product = e.target.value;
        this.setState({alert: "Product Added to Cart"});
        setTimeout(
            function() {
                this.setState({alert: ""});
            }
            .bind(this),
            3000
        );
            this.products.push(product);
            localStorage.setItem('products', JSON.stringify(this.products))
      }

      componentDidMount()
      {
        var arr = _.values(JSON.parse(localStorage.getItem('products')));
        if(arr.length > 0)
        {
        this.products = JSON.parse(localStorage.getItem('products'));
        }
      }

    render() {
        return (
            
            <div>
                 <p>{this.state.alert}</p>
             <div className="row">
             <div className="col-sm-5"></div>
             <div className="col-sm-4"></div>
             <div className="col-sm-2 cart"><Link to="/cart/"><button className="btn btn-primary margin-button">
            View Cart</button></Link>
                </div>               
             
             </div>
               
            <div className="row top-row-margin">
            <div className="col-sm-4 image-pointer" onClick={this.handleiPhone8Show}>
            <Iphone8/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXShow}>
            <Iphonex/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXSShow}>
            <Iphonexs/>
                </div>
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>$849</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>import React, { Component } from 'react';
import Iphone8 from "./iPhones/iphone8"
import Iphonex from "./iPhones/iphonex"
import Iphonexs from "./iPhones/iphonexs"
import "./layout.css";
import { Modal, Button } from 'react-bootstrap';
import { Link } from "gatsby";
import _ from "lodash";

class Home extends Component {
    products = [];
    constructor(props) {
        super(props);
        this.state = {
            iPhone8Show: false,
            iPhoneXShow: false,
            iPhoneXSShow: false,
            alert: "",
        };
        this.handleiPhone8Show = this.handleiPhone8Show.bind(this);
        this.handleiPhone8Close = this.handleiPhone8Close.bind(this);
        this.handleiPhoneXShow = this.handleiPhoneXShow.bind(this);
        this.handleiPhoneXClose = this.handleiPhoneXClose.bind(this);
        this.handleiPhoneXSShow = this.handleiPhoneXSShow.bind(this);
        this.handleiPhoneXSClose = this.handleiPhoneXSClose.bind(this);
    }

    handleiPhone8Close() {
        this.setState({ iPhone8Show: false });
      }
    
      handleiPhone8Show() {
        this.setState({ iPhone8Show: true });
      }
      handleiPhoneXClose() {
        this.setState({ iPhoneXShow: false });
      }
    
      handleiPhoneXShow() {
        this.setState({ iPhoneXShow: true });
      }
      handleiPhoneXSClose() {
        this.setState({ iPhoneXSShow: false });
      }
    
      handleiPhoneXSShow() {
        this.setState({ iPhoneXSShow: true });
      }

    //   Add products to cart
      addToCart = (e)=>
      {
        var product = e.target.value;
        this.setState({alert: "Product Added to Cart"});
        setTimeout(
            function() {
                this.setState({alert: ""});
            }
            .bind(this),
            3000
        );
            this.products.push(product);
            localStorage.setItem('products', JSON.stringify(this.products))
      }

      componentDidMount()
      {
        var arr = _.values(JSON.parse(localStorage.getItem('products')));
        if(arr.length > 0)
        {
        this.products = JSON.parse(localStorage.getItem('products'));
        }
      }

    render() {
        return (
            
            <div>
                 <p>{this.state.alert}</p>
             <div className="row">
             <div className="col-sm-5"></div>
             <div className="col-sm-4"></div>
             <div className="col-sm-2 cart"><Link to="/cart/"><button className="btn btn-primary margin-button">
            View Cart</button></Link>
                </div>               
             
             </div>
               
            <div className="row top-row-margin">
            <div className="col-sm-4 image-pointer" onClick={this.handleiPhone8Show}>
            <Iphone8/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXShow}>
            <Iphonex/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXSShow}>
            <Iphonexs/>
                </div>
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>$849</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>$1149</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>$1449</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>iPhone 8</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>iPhone X</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>iPhone XS</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphone8"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneX"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneXS"}>Add to Cart</button></div>               
                </div>

                
               

            {/* Modal for iPhone 8 info */}
        <Modal show={this.state.iPhone8Show} onHide={this.handleiPhone8Close}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone 8</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">4.7 inches, 60.9 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11, Upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 2GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 1821mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$849</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhone8Close} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

        {/* Modal for iPhone x */}
        <Modal show={this.state.iPhoneXShow} onHide={this.handleiPhoneXClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone X</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11.1.1, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 3 GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2716 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1149</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

         {/* Modal for iPhone xs */}
         <Modal show={this.state.iPhoneXSShow} onHide={this.handleiPhoneXSClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone XS</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2018, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 12, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256/512 GB,4GBRAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2658 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1449</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXSClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>


                </div>
        )}
}

export default Home;
149</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>import React, { Component } from 'react';
import Iphone8 from "./iPhones/iphone8"
import Iphonex from "./iPhones/iphonex"
import Iphonexs from "./iPhones/iphonexs"
import "./layout.css";
import { Modal, Button } from 'react-bootstrap';
import { Link } from "gatsby";
import _ from "lodash";

class Home extends Component {
    products = [];
    constructor(props) {
        super(props);
        this.state = {
            iPhone8Show: false,
            iPhoneXShow: false,
            iPhoneXSShow: false,
            alert: "",
        };
        this.handleiPhone8Show = this.handleiPhone8Show.bind(this);
        this.handleiPhone8Close = this.handleiPhone8Close.bind(this);
        this.handleiPhoneXShow = this.handleiPhoneXShow.bind(this);
        this.handleiPhoneXClose = this.handleiPhoneXClose.bind(this);
        this.handleiPhoneXSShow = this.handleiPhoneXSShow.bind(this);
        this.handleiPhoneXSClose = this.handleiPhoneXSClose.bind(this);
    }

    handleiPhone8Close() {
        this.setState({ iPhone8Show: false });
      }
    
      handleiPhone8Show() {
        this.setState({ iPhone8Show: true });
      }
      handleiPhoneXClose() {
        this.setState({ iPhoneXShow: false });
      }
    
      handleiPhoneXShow() {
        this.setState({ iPhoneXShow: true });
      }
      handleiPhoneXSClose() {
        this.setState({ iPhoneXSShow: false });
      }
    
      handleiPhoneXSShow() {
        this.setState({ iPhoneXSShow: true });
      }

    //   Add products to cart
      addToCart = (e)=>
      {
        var product = e.target.value;
        this.setState({alert: "Product Added to Cart"});
        setTimeout(
            function() {
                this.setState({alert: ""});
            }
            .bind(this),
            3000
        );
            this.products.push(product);
            localStorage.setItem('products', JSON.stringify(this.products))
      }

      componentDidMount()
      {
        var arr = _.values(JSON.parse(localStorage.getItem('products')));
        if(arr.length > 0)
        {
        this.products = JSON.parse(localStorage.getItem('products'));
        }
      }

    render() {
        return (
            
            <div>
                 <p>{this.state.alert}</p>
             <div className="row">
             <div className="col-sm-5"></div>
             <div className="col-sm-4"></div>
             <div className="col-sm-2 cart"><Link to="/cart/"><button className="btn btn-primary margin-button">
            View Cart</button></Link>
                </div>               
             
             </div>
               
            <div className="row top-row-margin">
            <div className="col-sm-4 image-pointer" onClick={this.handleiPhone8Show}>
            <Iphone8/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXShow}>
            <Iphonex/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXSShow}>
            <Iphonexs/>
                </div>
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>$849</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>$1149</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>$1449</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>iPhone 8</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>iPhone X</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>iPhone XS</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphone8"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneX"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneXS"}>Add to Cart</button></div>               
                </div>

                
               

            {/* Modal for iPhone 8 info */}
        <Modal show={this.state.iPhone8Show} onHide={this.handleiPhone8Close}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone 8</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">4.7 inches, 60.9 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11, Upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 2GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 1821mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$849</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhone8Close} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

        {/* Modal for iPhone x */}
        <Modal show={this.state.iPhoneXShow} onHide={this.handleiPhoneXClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone X</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11.1.1, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 3 GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2716 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1149</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

         {/* Modal for iPhone xs */}
         <Modal show={this.state.iPhoneXSShow} onHide={this.handleiPhoneXSClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone XS</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2018, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 12, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256/512 GB,4GBRAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2658 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1449</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXSClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>


                </div>
        )}
}

export default Home;
449</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>iPhone 8</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>iPhone X</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>iPhone XS</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphone8"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneX"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneXS"}>Add to Cart</button></div>               
                </div>

                
               

            {/* Modal for iPhone 8 info */}
        <Modal show={this.state.iPhone8Show} onHide={this.handleiPhone8Close}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone 8</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">4.7 inches, 60.9 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11, Upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 2GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 1821mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$849</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhone8Close} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

        {/* Modal for iPhone x */}
        <Modal show={this.state.iPhoneXShow} onHide={this.handleiPhoneXClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone X</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11.1.1, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 3 GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2716 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">import React, { Component } from 'react';
import Iphone8 from "./iPhones/iphone8"
import Iphonex from "./iPhones/iphonex"
import Iphonexs from "./iPhones/iphonexs"
import "./layout.css";
import { Modal, Button } from 'react-bootstrap';
import { Link } from "gatsby";
import _ from "lodash";

class Home extends Component {
    products = [];
    constructor(props) {
        super(props);
        this.state = {
            iPhone8Show: false,
            iPhoneXShow: false,
            iPhoneXSShow: false,
            alert: "",
        };
        this.handleiPhone8Show = this.handleiPhone8Show.bind(this);
        this.handleiPhone8Close = this.handleiPhone8Close.bind(this);
        this.handleiPhoneXShow = this.handleiPhoneXShow.bind(this);
        this.handleiPhoneXClose = this.handleiPhoneXClose.bind(this);
        this.handleiPhoneXSShow = this.handleiPhoneXSShow.bind(this);
        this.handleiPhoneXSClose = this.handleiPhoneXSClose.bind(this);
    }

    handleiPhone8Close() {
        this.setState({ iPhone8Show: false });
      }
    
      handleiPhone8Show() {
        this.setState({ iPhone8Show: true });
      }
      handleiPhoneXClose() {
        this.setState({ iPhoneXShow: false });
      }
    
      handleiPhoneXShow() {
        this.setState({ iPhoneXShow: true });
      }
      handleiPhoneXSClose() {
        this.setState({ iPhoneXSShow: false });
      }
    
      handleiPhoneXSShow() {
        this.setState({ iPhoneXSShow: true });
      }

    //   Add products to cart
      addToCart = (e)=>
      {
        var product = e.target.value;
        this.setState({alert: "Product Added to Cart"});
        setTimeout(
            function() {
                this.setState({alert: ""});
            }
            .bind(this),
            3000
        );
            this.products.push(product);
            localStorage.setItem('products', JSON.stringify(this.products))
      }

      componentDidMount()
      {
        var arr = _.values(JSON.parse(localStorage.getItem('products')));
        if(arr.length > 0)
        {
        this.products = JSON.parse(localStorage.getItem('products'));
        }
      }

    render() {
        return (
            
            <div>
                 <p>{this.state.alert}</p>
             <div className="row">
             <div className="col-sm-5"></div>
             <div className="col-sm-4"></div>
             <div className="col-sm-2 cart"><Link to="/cart/"><button className="btn btn-primary margin-button">
            View Cart</button></Link>
                </div>               
             
             </div>
               
            <div className="row top-row-margin">
            <div className="col-sm-4 image-pointer" onClick={this.handleiPhone8Show}>
            <Iphone8/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXShow}>
            <Iphonex/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXSShow}>
            <Iphonexs/>
                </div>
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>$849</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>$1149</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>$1449</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>iPhone 8</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>iPhone X</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>iPhone XS</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphone8"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneX"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneXS"}>Add to Cart</button></div>               
                </div>

                
               

            {/* Modal for iPhone 8 info */}
        <Modal show={this.state.iPhone8Show} onHide={this.handleiPhone8Close}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone 8</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">4.7 inches, 60.9 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11, Upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 2GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 1821mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$849</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhone8Close} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

        {/* Modal for iPhone x */}
        <Modal show={this.state.iPhoneXShow} onHide={this.handleiPhoneXClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone X</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11.1.1, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 3 GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2716 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1149</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

         {/* Modal for iPhone xs */}
         <Modal show={this.state.iPhoneXSShow} onHide={this.handleiPhoneXSClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone XS</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2018, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 12, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256/512 GB,4GBRAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2658 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1449</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXSClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>


                </div>
        )}
}

export default Home;
149</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

         {/* Modal for iPhone xs */}
         <Modal show={this.state.iPhoneXSShow} onHide={this.handleiPhoneXSClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone XS</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2018, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 12, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256/512 GB,4GBRAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2658 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">import React, { Component } from 'react';
import Iphone8 from "./iPhones/iphone8"
import Iphonex from "./iPhones/iphonex"
import Iphonexs from "./iPhones/iphonexs"
import "./layout.css";
import { Modal, Button } from 'react-bootstrap';
import { Link } from "gatsby";
import _ from "lodash";

class Home extends Component {
    products = [];
    constructor(props) {
        super(props);
        this.state = {
            iPhone8Show: false,
            iPhoneXShow: false,
            iPhoneXSShow: false,
            alert: "",
        };
        this.handleiPhone8Show = this.handleiPhone8Show.bind(this);
        this.handleiPhone8Close = this.handleiPhone8Close.bind(this);
        this.handleiPhoneXShow = this.handleiPhoneXShow.bind(this);
        this.handleiPhoneXClose = this.handleiPhoneXClose.bind(this);
        this.handleiPhoneXSShow = this.handleiPhoneXSShow.bind(this);
        this.handleiPhoneXSClose = this.handleiPhoneXSClose.bind(this);
    }

    handleiPhone8Close() {
        this.setState({ iPhone8Show: false });
      }
    
      handleiPhone8Show() {
        this.setState({ iPhone8Show: true });
      }
      handleiPhoneXClose() {
        this.setState({ iPhoneXShow: false });
      }
    
      handleiPhoneXShow() {
        this.setState({ iPhoneXShow: true });
      }
      handleiPhoneXSClose() {
        this.setState({ iPhoneXSShow: false });
      }
    
      handleiPhoneXSShow() {
        this.setState({ iPhoneXSShow: true });
      }

    //   Add products to cart
      addToCart = (e)=>
      {
        var product = e.target.value;
        this.setState({alert: "Product Added to Cart"});
        setTimeout(
            function() {
                this.setState({alert: ""});
            }
            .bind(this),
            3000
        );
            this.products.push(product);
            localStorage.setItem('products', JSON.stringify(this.products))
      }

      componentDidMount()
      {
        var arr = _.values(JSON.parse(localStorage.getItem('products')));
        if(arr.length > 0)
        {
        this.products = JSON.parse(localStorage.getItem('products'));
        }
      }

    render() {
        return (
            
            <div>
                 <p>{this.state.alert}</p>
             <div className="row">
             <div className="col-sm-5"></div>
             <div className="col-sm-4"></div>
             <div className="col-sm-2 cart"><Link to="/cart/"><button className="btn btn-primary margin-button">
            View Cart</button></Link>
                </div>               
             
             </div>
               
            <div className="row top-row-margin">
            <div className="col-sm-4 image-pointer" onClick={this.handleiPhone8Show}>
            <Iphone8/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXShow}>
            <Iphonex/>
                </div>
                <div className="col-sm-4 image-pointer" onClick={this.handleiPhoneXSShow}>
            <Iphonexs/>
                </div>
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>$849</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>$1149</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>$1449</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name" onClick={this.handleiPhone8Show}>iPhone 8</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXShow}>iPhone X</div>
                 <div className="col-sm-4 product-name" onClick={this.handleiPhoneXSShow}>iPhone XS</div>                
                </div>
                <div className="row">
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphone8"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneX"}>Add to Cart</button></div>
                 <div className="col-sm-4 product-name"><button className="btn btn-primary margin-button" onClick={this.addToCart} value={"iphoneXS"}>Add to Cart</button></div>               
                </div>

                
               

            {/* Modal for iPhone 8 info */}
        <Modal show={this.state.iPhone8Show} onHide={this.handleiPhone8Close}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone 8</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">4.7 inches, 60.9 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11, Upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 2GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 1821mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$849</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhone8Close} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

        {/* Modal for iPhone x */}
        <Modal show={this.state.iPhoneXShow} onHide={this.handleiPhoneXClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone X</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2017, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 11.1.1, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256 GB, 3 GB RAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2716 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1149</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>

         {/* Modal for iPhone xs */}
         <Modal show={this.state.iPhoneXSShow} onHide={this.handleiPhoneXSClose}>
          <Modal.Header closeButton>
            <Modal.Title>Apple iPhone XS</Modal.Title>
          </Modal.Header>
          <Modal.Body>
              <p><span>Announced:</span> <span className="modal-float-right">2018, September</span></p>
              <p><span>Display:</span> <span className="modal-float-right">5.8 inches, 84.4 cm2</span></p>
              <p><span>OS:</span> <span className="modal-float-right">iOS 12, upgradable</span></p>
              <p><span>Memory:</span> <span className="modal-float-right">64/256/512 GB,4GBRAM</span></p>
              <p><span>Battery:</span> <span className="modal-float-right">Li-Ion 2658 mAh</span></p>
              <p><span>Price:</span> <span className="modal-float-right">$1449</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXSClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>


                </div>
        )}
}

export default Home;
449</span></p>


          </Modal.Body>
          <Modal.Footer>
            <Button variant="primary" onClick={this.handleiPhoneXSClose} className="margin-button">
              Close
            </Button>
          </Modal.Footer>
        </Modal>


                </div>
        )}
}

export default Home;

This component is stateful, not a stateless component as most of the Gatsby components usually are.

In this component, we have shown three products which all are iPhones. Main this is that images of these iPhones are kept in a folder and called through a different component. At line number 91, 94, and 97 you can check how these are imported to home.

Here we used the bootstrap modal to show the specifications of the products. Let us explain the working of the main methods.

addToCart(): This is an event-driven method and pushes the product to an array when the user clicks on the add to cart.

handleiPhone8Close() and handleiPhone8Show(): These are the handlers for bootstrap modals which are used to show the specifications of products.

iPhones Component

The iPhone folder has three components named iphone8.js, iphonex.js, and iphonexs.js. These components only used to add images to other components. We used these components in home page. Actually, these components usefor this purpose which makes the images loading very fast on websites. Check the code of one image component: components/iPhones/iphone8.js

import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"

const Iphone8 = () => (
  <StaticQuery
    query={graphql`
      query {
        placeholderImage: file(relativePath: { eq: "apple-iphone-8-plus-0.jpg" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
  />
  
)
    export default Iphone8

Cart Component

When the user added products to the cart and click the Show Cart button, then flow of the app goes to another page cart.js. Let’s check the code of this page: src/pages/cart.js

import React, { Component } from 'react';
import { Link } from "gatsby"
import _ from "lodash";
import { Modal } from 'react-bootstrap';
import cosmicService from './../services/cosmicService';

const Iphone8 = (props) => {
    return <div>
        <img src={require('../images/apple-iphone-8-plus-0.jpg')} className="cart-image" alt="iphone8"/>
        <h6 className="cart-pro-text">iPhone 8</h6>
    </div>
}

const IphoneX = (props) => {
    return <div>
        <img src={require('../images/apple-iphone-x-new-1.jpg')} className="cart-image" alt="iphonex" />
        <h6 className="cart-pro-text">iPhone X</h6>

    </div>
}

const IphoneXS = (props) => {
    return <div>
        <img src={require('../images/iphone-xs-img.jpg')} className="cart-image" alt="iphonexs" />
        <h6 className="cart-pro-text">iPhone XS</h6>
    </div>
}

class Cart extends Component {
    productArray = [];
    constructor(props) {
        super(props);
        this.state = {
            isEmpty: "false",
            message: 'My Cart is:',
            iphone8: false,
            iphoneX: false,
            iphoneXS: false,
            nav: true,
            checkoutShow: false,
            userName: '',
            address: '',
            cardNumber: '',
            cvv: '',
            cardExpiryDate: '',
            mobile: '',
            amount:'',
            isLoading: '',
            dynamic: '',
        };
        this.handleCheckoutShow = this.handleCheckoutShow.bind(this);
        this.handleCheckoutClose = this.handleCheckoutClose.bind(this);
        this.emptyCart = this.emptyCart.bind(this);
    }

    // getting products which are in cart
    getProducts() {
        this.productArray = _.values(JSON.parse(localStorage.getItem('products')));
        if (this.productArray.length < 1) {
            this.setState({ isEmpty: "true" });
            this.setState({ dynamic: 'dynamic' });
            this.setState({ message: "Your Cart is Empty" });
            this.setState({ nav: false });
        }
    }

    componentDidMount() {
        this.getProducts();
        this.checkingCart();

    }

    //checking products in Cart
    checkingCart() {
        var amount = 0;
        if (this.productArray.indexOf('iphone8') >= 0) {
            this.setState({ iphone8: true })
            amount = amount + 849;
        }

        if (this.productArray.indexOf('iphoneX') >= 0) {
            this.setState({ iphoneX: true });
            amount = amount + 1149;
        }

        if (this.productArray.indexOf('iphoneXS') >= 0) {
            this.setState({ iphoneXS: true })
            amount = amount + 1449;
        }
        this.setState({amount: amount})
    }

    handleCheckoutShow() {
        this.setState({ checkoutShow: true });
    }

    handleCheckoutClose() {
        this.setState({ checkoutShow: false });
    }

    onChange = (e) => {
        const state = this.state
        state[e.target.name] = e.target.value;
        this.setState(state);
    }

    emptyCart()
    {
        localStorage.removeItem('products');
        
    }

    onSubmit = (e) =>
    {
        this.setState({isLoading: 'Placing order...'})
      e.preventDefault();
        cosmicService.placeOrder(this.state.userName, this.state.address, this.state.cardNumber, this.state.cvv, this.state.cardExpiryDate, this.state.mobile, this.state.amount)
        .then((result)=>{
            this.setState({isLoading: 'Order successfully placed!'});
            setTimeout(() => {
                this.setState({checkoutShow: false});
                localStorage.removeItem('products');
              }, 3000);
        })
    }

    render() {
        return (
            <div>
                <div className="jumbotron"><b>Gatsby Ecommerce App in Cosmic JS</b></div>
                <div><Link to="/"><button className="btn btn-primary margin-button ">
                    Back</button></Link></div>
                <div className="container h-100 d-flex justify-content-center">

                    <div className="row">
                        <div>
                            <h1>{this.state.message}</h1>
                            <div className="">
                            {this.state.iphone8 ? <Iphone8 /> : null}
                            {this.state.iphoneX ? <IphoneX /> : null}
                            {this.state.iphoneXS ? <IphoneXS /> : null}
                            </div>
                            <div className="button-padding">
                            <div className={this.state.dynamic}><Link to="/"><button className="btn btn-danger" onClick={this.emptyCart}>
                                Empty Cart</button></Link>
                                
                                <button className="btn btn-primary margin-button" onClick={this.handleCheckoutShow}>
                                    Checkout</button></div>
                                    </div>

                        </div>

                    </div>
                </div>
                <Modal show={this.state.checkoutShow} onHide={this.handleCheckoutClose}>
                    <Modal.Header closeButton>
                        <Modal.Title>Checkout</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <form onSubmit={this.onSubmit}>

                            <p><input type="text" name="userName" value={this.state.userName} onChange={this.onChange} placeholder="Enter your name" className="form-control"/></p>
                            <p><input type="text" name="address" value={this.state.address} onChange={this.onChange} placeholder="Enter your address" className="form-control" /></p>
                            <p><input type="text" name="cardNumber" value={this.state.cardNumber} onChange={this.onChange} placeholder="Enter your card number"  className="form-control"/></p>
                            <p><input type="text" name="cvv" value={this.state.cvv} onChange={this.onChange} placeholder="Enter your cvv" className="form-control" /></p>
                            <p><input type="text" name="cardExpiryDate" value={this.state.cardExpiryDate} onChange={this.onChange} placeholder="Enter card's expiry date" className="form-control" /></p>
                            <p><input type="text" name="mobile" value={this.state.mobile} onChange={this.onChange} placeholder="Enter your mobile"  className="form-control"/></p>
                            <p><span>Total Amount:</span><span>${this.state.amount}</span></p>

                            <p><input type="submit" value="Place Order" className="margin-button btn btn-primary"/></p>   
                            <p>{this.state.isLoading}</p>                        

                        </form>
                    </Modal.Body>                    
                </Modal>
            </div>
        )
    }

}
export default Cart;

Let us explain each method of cart.js:

getProducts(): In this method, we are getting the products which are stored in the cart. For cart, we temporary stores the products in local storage. That means this method is getting the products from local storage.

checkingCart(): This method is checking that which product is added to the cart that means this method is filtering the products and calculating the price.

onSubmit(): This is an event-driven method, which collecting the details of the order along with user billing details and passing to the method placeOrder() in the cosmicService.

Cosmic Service

This is the only service in this app which hits the Cosmic JS API and stores the data to Cosmic JS database. Check the code: src/services/cosmicService.js

import config from './../config/config';
import axios from 'axios';

const cosmicService = {

    placeOrder(userName, address, cardNumber, cvv, cardExpiryDate, mobile, amount)
    {
        return axios.post(config.url+config.bucket_slug+"/add-object/", {
            title: userName, slug: userName + cardNumber, type_slug: 'orders', write_key: config.write_key,
            metafields: [
                {
                  key: "userName",
                  type: "text",
                  value: userName
                },
                {
                    key: "address",
                    type: "text",
                    value: address
                  },
                  {
                    key: "cardNumber",
                    type: "text",
                    value: cardNumber
                  },
                  {
                    key: "cvv",
                    type: "text",
                    value: cvv
                  },
                  {
                    key: "cardExpiryDate",
                    type: "text",
                    value: cardExpiryDate
                  },
                  {
                    key: "mobile",
                    type: "text",
                    value: mobile
                  },
                  {
                    key: "totalamount",
                    type: "text",
                    value: amount
                  }
            ]
        })
    }
}

export default cosmicService;

There is only one method in this service named placeOrder() which accepts the seven arguments. It hits the post request to the Cosmic JS server to save the data. Here we are providing write access key for taking the permission of writing on the Cosmic JS database. This is an example of storing information in Cosmic JS; however, it’s never advised to store credit card data in Cosmic JS.

What Functionality We Have Implemented?

Till now we have implemented the complete functionality on the development server. That means we can use the complete functionality of the app in development mode. Because it is a Gatsby app created with npm CLI, so it is deployable on any server which allows deployment from node.js app. Here we deployed our app on Heroku server.

We created this app with Gatsby CLI and used React.js also to make some components stateful. After using this app, you will understand the power of Cosmic JS because of its blazing speed.

Conclusion

With the help of Cosmic JS we can create powerful apps and can use the Cosmic JS database for fast data processing. Here we created and configured a Gatsby.js app with Cosmic JS without any difficulty. You don’t need to install any extra efforts to configure and use Cosmic JS APIs.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI


Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]