Quite a number of us like to order food. How about we track the delivery of meals right from placing our order to its delivery. In this article, we would be building a food delivery tracking progressive web app (PWA) using Pusher and Vue.js.

Here is what the final demo would look like:

Background

A progressive web app is simply an app that employs various modern technologies to achieve a unique goal. In this article, we will be building a PWA that can engage the user even when they lose connectivity.

To achieve this realtime feature, we will be using Pusher. Pusher is a leader in realtime technologies, and allows us to perform various operations on the web in realtime. Our offline starter project will be an enhanced Vue PWA webpack template. Also, we will be making use of Progressbar.js to implement a smart progress bar functionality on our app and Bulma classes to style our app.

Requirements

Knowledge of HTML, CSS JavaScript and Vue is required, along with the following tools:

  • Node
  • Vue-cli
  • Pusher
  • Progressbar.js
  • Bulma

Setup

Install Vue

We will be working with vue-cli, which you can install with:

    npm install vue-cli -g

This installs the latest version of Vue CLI globally on your machine. Webpack has a PWA template and we will work with this in building our app. Create a Vue project with the pwa template. This is the syntax for creating a project with a template in Vue:

    vue init <template> <project-name>

For our app, in the command prompt we run:

    vue init pwa pusher-vue-pwa

Several popup commands requesting some project details will be displayed on our console. For the purpose of this project, skip all of them and use all default values provided. You can customize these if you choose though.

Now let’s test our app, run:

    cd pusher-vue-pwa // Changes directory to our project folder
    npm install //Installs all dependencies required
    npm run dev //Serves our app locally.

You should get a welcome screen:

Install Dependencies

Next, let’s install our dependencies with:

    npm install bulma progressbar.js pusher pusher-js dotenv --save
  • Bulma: CSS framework based on flexbox
  • Progressbar.js: Used to animate SVG paths
  • Pusher: Provides realtime service (server-side)
  • Pusher-js: Provides realtime service (client-side)
  • Dotenv: Used to load environment variables

dotenv is used to load environmental variables from a .env file in our root folder. Our pusher keys will be saved in this file. No pusher keys yet? You’ll get them next.

Create a Pusher Account

Go on to Pusher and create an account. On the left nav bar, create a new app with any name of your choice. You will be issued an app-id, a pusher key, and a pusher-secret. Select a cluster near you and keep these credentials safe; we will require them later in our app.

Configure a Server

For our delivery app, we will configure our pusher server with the pusher credentials obtained on Pusher account creation. In our root folder, we create a file .env and pass in our credentials:

**/.env**

    PUSHER_APP_ID=XXXXXXXXXX
    PUSHER_KEY=XXXXXXX
    PUSHER_SECRET=XXXXXXX
    TIME=5000

This file will be utilized by dotenv, which we installed earlier.

Create a file in the root directory named server.js, here we shall configure our server. First, we require dotenv and apply the .config() method to it. This allows us to use the process.env object.

    require('dotenv').config();
    const Pusher = require('pusher');
    const { PUSHER_APP_ID, PUSHER_KEY, PUSHER_SECRET, TIME } = process.env;

    const pusher = new Pusher({
      appId: PUSHER_APP_ID,
      key: PUSHER_KEY,
      secret: PUSHER_SECRET,
      cluster: 'eu',
      encrypted: true
    });

As seen above, the ES6 destructuring technique is used to assign the data in our .env object to the listed constants. Next, we create a new pusher instance and assign our pusher credentials to their respective object properties as seen above.

For our demo we shall use a setInterval() function to simulate the timing of the pizza delivery process. Let’s configure this timing function:

    let stage = 1;
    const interval = setInterval(() => {
      const messages = {
        1: "Order Received",
        2: "Order Placed",
        3: "In the Oven",
        4: "Out for Delivery",
        5: "Delivered"
      }
      stage = stage + 1;
      const messageId = stage-1;
      if (stage > 5) {
        console.log('clearing');
        clearInterval(interval);
      }

      pusher.trigger('food', 'status', {
        message: messages[messageId],
        progress: messageId/5
      });
    }, TIME);

We created a stage variable to keep track of the iteration. In our setInterval() function, we pass it the usual callback using the ES6 arrow function. In this function, we create an object containing the individual processes as values with their properties being numbered keys. The stage value is incremented by one for every iteration. This ensures that at the last stage, the interval is cleared out and exited.

We created a Message ID to refer to the message used from the array, and then converted that to a fraction to serve as the progress bar as well. This serves as our progress. The if block creates a termination case for our function based on the value of messageId. As long as the function is not terminated, we keep calling the trigger method on the pusher instance, passing it arguments of channel, event, and a payload. This payload is an object containing data we would like to send over our pusher channel.

Create a Client with Vue

Vue is used to create the client interface as stated earlier. In our src folder, there is an already configured Vue component — App.vue. Delete all the content in it and let’s get to creating our own content. Add the following template to represent the UI:

**/src/App.vue**

     <template>
      <section class="hero is-danger is-fullheight">
        <div class="notification is-warning" v-show="!connectivityStatus">
          <button class="delete"></button>
          {{connectivityText}}
        </div>
        <div class="hero-body">
          <div class="container">
            <div class="level">
              <div class="level-item has-text-centered">
                <div>
                  <status :progress="progress"></status>
                  <h1 class="title">{{statusText}}</h1>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </template>

Notice the <status> component and the :progress binding? Their values are received from the component’s object as shown below:

**/src/App.vue**

    <script>
    require('../node_modules/bulma/css/bulma.css');
    import pusher from 'pusher-js';
    import Status from '@/components/Status';
    export default {
      data() {
        return {
          statusText: '',
          progress: 0,
          connectivityText: '',
          connectivityStatus: true,
        }
      },
      created() {
        var pusher = new Pusher('API_KEY', {
          cluster: 'eu',
          encrypted: true
        });
        var channel = pusher.subscribe('food');
        channel.bind('status', (data) => {
          console.log(data)
          this.statusText = data.message;
          this.progress = data.progress;
        });
      },
      components: {
        'status': Status
      }
    }
    </script>

First, we require bulma, this provides all the bulma classes used to style our app in the template.

Next, we import pusher-js which we installed at the beginning. A Status custom component is also imported which we will create soon. In our Vue data method, we create and return an object whose properties values will be used in the template. The statusText property displays the status of our order.

The value of connectivityText is displayed whenever our device is offline and this depends on the value of the connectivityStatus property to be visible or not. We will set these values soon.

In the created() lifecycle method, we create a new pusher instance on the client side. This instance receives the payload from the server once we subscribe to our channel created on the server.

Note: Multiple events can be created per channel.

After a new pusher instance is created with our pusher-key (obtained on registration) as seen above. With this instance, we can subscribe to the channel we used on the server. Next, bind the status event to channel, passing it a callback which fetches the payload from the channel. The data fetched is passed as values to the properties we created in our data() method.

Progress Status Component

In the components folder, delete the Hello.vue component and create a Status.vue file. You also need to replace Hello.vue with Status.vue in the routes list if you opted for routing when creating with Vue CLI.

Add a div with a status class to the template as shown below:

    <template>
      <div class="status"></div>
    </template>

The div tag serves as a mount point for the progress status widget. Next, create the component’s logic that imports the progressbar plugin:

    <script>
    import ProgressBar from 'progressbar.js';
    export default {
      data() {
        return {
          bar: null
        }
      },
      props: ['progress'],
      watch: {
        progress(val) {
          this.bar.animate(val);
        }
      },
      mounted() {
        this.bar = new ProgressBar.Circle(this.$el, {
          color: '#FFEA82',
          trailColor: '#eee',
          trailWidth: 1,
          duration: 1400,
          easing: 'bounce',
          strokeWidth: 6,
          from: { color: '#d6ff82', a: 0 },
          to: { color: '#5aedb4', a: 1 },
          // Set default step function for all animate calls
          step: function(state, circle) {
            circle.path.setAttribute('stroke', state.color);
          }
        });
        this.bar.animate(this.progress);
      }
    }
    </script>

The component has a bar property which is used to keep track of the widget configuration instance. It is used to configure the awesome circular status bar.

We configure the Progress Bar in our mounted lifecycle method to ensure that the DOM is ready before manipulating it. This is done by creating an instance of the Circle constructor on the ProgressBar object. After configuring our circular bar, the .animate() object is called on bar and passed a parameter which is the value of progress property. The property is received from the parent component via props. This triggers an animation in the status bar but with a zero initial value so nothing is obvious.

Remember the :progress property we bound to the value of progress in App.vue? It would only be accessible to the Status child component if we specify it in the props array.

Now to a fun part; in the watch object, we state a progress function which listens for value changes on the progress property. Whenever the value changes, the new value is passed as a parameter to the animate method on this.bar. This means that whenever a new progress value is received from the server, it propagates through the App parent component, down to the child’s watch object and updates the status of our order. This update is observed from the progress circular bar.

If you don’t have the app running, run:

    npm run dev

Then start the server:

    node server.js

Once the server starts running and is emitting events, you should see the client update as shown in the video below:

Handling Offline

How do we handle notifications when offline?
We listen to the windows object for an offline event or an online event, in which case this.conectivityStatus is false or true respectively. When connectivityStatus is false, connectivityText resolves to:

    'You seem to be offline. Connect to see latest order status'

In the created() method of App.vue, let’s create an EventListener:

    created() {
        ...
        window.addEventListener('offline', () => {
          this.connectivityStatus = false;
          this.connectivityText = 'You seem to be offline. Connect to see latest order status';
        })
        window.addEventListener('online', () => {
          console.log('asd')
          this.connectivityStatus = true;
        })
      },
    ...

While the app is running, turn off your network connectivity and you should see a warning message pop-up on the screen as shown in the image below:

Conclusion

In this article, we built a realtime delivery tracking PWA using Pusher and Vue while implementing status bar features with Progressbar.js and styling with Bulma. This app has minimal styling, feel free to add more styles and possibly more cool functionalities. You can find the source code here.

About Chris Nwamba

Chris is a JavaScript preacher. He also strives to make something out of other languages. Tech Writer. Dev Evangelist. Speaker.