Build a realtime Instagram clone — Part 4: Going offline with service workers

  • Christian Nwamba
April 27th, 2018
You should have completed the previous parts of the series.

This is part 4 of a 4 part tutorial. You can find part 1 here, part 2 here and part 3 here.

In the last part of the series, we looked at how to add realtime functionality to our React application using Pusher to enable notifications. Sometimes, when surfing the web, you loose internet connection. In the past, all you got was the default error page decided by the browser. Now, you sometimes get custom pages even when you don’t have internet connection at all.

In this article, we are going to look at how to add this kind of functionality to our application to allow the users still engage with our application even when they are constrained by internet connections. To do accomplish this, we are going to make use of the browser’s local storage and service workers.

Prerequisites

To follow this article you need the following:

  • Should have read previous parts of the series
  • Basic knowledge of JavaScript
  • Node installed on your machine
  • NPM installed on your machine

Set up an app shell to show when offline

The app “shell” is the minimal HTML, CSS and JavaScript required to power the user interface. This allow us to immediately render the page while the rest of the page is being fetched.

Service workers

Service workers are scripts that the browser runs in the background to give the online effect to users by caching assets and other files. Their core features are how they’re able to intercept and handle network requests. There are three stages in the lifecycle of a service worker: registration, installation and activation.

React includes starter code that registers a service worker. In the src/index.js you have:

    // src/index.js
    [...]
    import registerServiceWorker from './registerServiceWorker';
    [...]
    registerServiceWorker();

This registers a service worker for your application when your application is in production mode.

Next thing to do is update your public/manifest.json file

    {
      "short_name": "InstaClone",
      "name": "Simple Instagram Clone App",
      "icons": [
        {
          "src": "favicon.ico",
          "sizes": "64x64 32x32 24x24 16x16",
          "type": "image/x-icon"
        }
      ],
      "start_url": "./index.html",
      "display": "standalone",
      "theme_color": "#000000",
      "background_color": "#ffffff"
    }

Now, build your application using:

    npm run build # or yarn build

An optimized version of your application will be built in the build/ folder of your application. Now you will want to deploy the built application. To do this, http-server - a node module for serving static files:

    npm install http-server
    http-server build

When you visit the application at 127.0.0.1:8080, you get your regular application. Now, head over to the Appication tab of your Chrome debug console. You can see the existing service worker for your application displayed there. Click the Offline option to simulate no network connection. When you reload your application, you get this:

Serving stale data when offline

The current display when a user is offline is a little better than the default page shown when there’s no connection. For an application like our Instagram clone application, it’ll be nice for the users to still be able to view old posts when offline. When we fetch posts in the Posts component, we are going to save them in the browsers localStorage for future use. To do this, update the componentDidMount of your src/components/Posts/index.js as follows:

    // src/components/Posts/index.js
    [...]
    componentDidMount(){
        [...]
        if( !navigator.onLine){
          this.setState({ posts: JSON.parse(localStorage.getItem("posts")) });
        }else{
          this.props.apollo_client
          .query(
            // grapgl ql query
            [...]
          )
          .then(response => {
            this.setState({ posts: response.data.posts});
            localStorage.setItem('posts', JSON.stringify(response.data.posts));
          });
        }
        [...]
      }

We first check if the user is online. If they are, the apollo_client ****makes the request to get new posts. After the posts are obtained they’re saved using the localStorage.setItem() function. When the user is offline, !navigator.onLine will return true and then the stored posts are fetched from the localStorage using localStorage.getItem().

Tip: localStorage only stores strings so to work around this, you use JSON.stringify() and JSON.parse() for storage and retrieval respectfully

You can also decide to display a banner to the user letting then know that they are viewing stale data. To do this, let’s create a simple Notifier component in the src/components directory like this:

    cd src/components
    mkdir Notifier
    cd Notifier && touch index.js Notifier.css
    // src/components/Notifier/index.js

    import React, { Component } from "react";
    import "./Notifier.css";
    class Notifier extends Component {
      render() {
        return (
          <div className="notify">
            <p>
              <em>{this.props.data}</em>
            </p>
          </div>
        );
      }
    }
    export default Notifier;

The component has the following styling:

    // src/components/Notifier/Notifier.css

    .notify{
        background-color: red;
        width: 100%;
        padding-top: 20px;
        padding-bottom: 20px;
        text-align: center;
        color: white;
        margin-bottom: 20px;
    }

Now that the component is created, to use it in the Posts component, update the src/components/Posts/index.js:

    // src/components/Posts/index.js

    import React, {Component} from "react";
    import "./Posts.css";
    import gql from "graphql-tag";
    import Post from "../Post";
    import Notifier from "../Notifier";
    class Posts extends Component {
      constructor() {
        super();
        this.state = {
          posts: []
        };
        this.offline = !navigator.onLine;
      }
      componentDidMount() {
        [...]
      }
      render() {
        const notify = this.offline ? <Notifier data="Instagram Clone: Offline Mode" /> : <span />;
        return (
          <div>
            {notify}
            // display posts
            [...]
          </div>
        );
      }
    }

    export default Posts;

Now, build the application again using:

    npm run build # or yarn build

Start your backend server:

    node server

If you are confused about the backend server, refer to previous parts of this series

And then serve the production build with:

    http-server build

When you go to the browser you get:

It’s advised to test service workers in incognito/private mode so that your application behavior is not affected by previously installed service workers / caches

Conclusion

In this series, we have seen how to build a simple Instagram clone using react by using react, fetching dynamic data using GraphQL, adding realtime functionality using Pusher and making the application work offline with service workers. Feel free to leverage any of the concepts shared here in your web applications. Here’s a link to the Github repository if interested

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.