Codementor Events

Build a realtime chart with Vue.js

Published May 04, 2018
Build a realtime chart with Vue.js

Data has become a very important part of our lives recently and making sense of that data is equally important. There is no point in having data if you cannot track or analyze it, especially if this data has anything to do with finances.

That’s why we will be building an expense and income tracker chart, with realtime features using Pusher. Our interactive dashboard will have a line chart that displays your income and expenses for each day. You’ll be able to add new expenses and income and see the chart update in real time.

The dashboard chart will be powered by Node.js + Express as the backend server and Vue + vue-chartjs for the frontend bootstrapped by vue-cli.

Scaffolding the app with vue-cli

vue-cli is a simple CLI for scaffolding Vue.js projects. We’ll install vue-cli and then use it to bootstrap the app using the webpack template, with the following commands:

npm install -g vue-cli

vue init webpack-simple realtime-chart-pusher
  • Tip: The webpack-simple template is a simple webpack + vue-loader setup for quick prototyping. You can read more about that here.

Setting up Node.js Server

Next thing to do is set up a server that will help us communicate with Pusher. I’m going to assume that both Node and npm are installed on your system. We will then install the dependencies we will be using for the Node server.

npm install body-parser express nodemon pusher
  • Tip: nodemon will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your node application.

One more thing, we are going to need an entry point/file for our Node server. We can do that by creating a server.js file in the root of the app.

Pusher Setup

To implement the realtime functionality, we’ll need the power of Pusher. If you haven’t already, sign up for a Pusher account and create a new app. When your new app is created, get your app_id, keys and cluster from the Pusher dashboard.

App Setup

Now that we have a Pusher account, and have installed the dependencies needed for the Node.js backend, let’s get building.

Let’s write code for the server.js file.

const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const app = express();
const Pusher = require('pusher');

const pusher = new Pusher({
    appId: 'YOUR_APP_ID',
    key: 'YOUR_APP_KEY',
    secret: 'YOUR_APP_SECRET',
    cluster: 'eu',
    encrypted: true
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname + '/app')));

app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});

Let’s have a look at what’s happening here. We require Express, path, body-parser and Pusher and we initialized express() with app.

We use body-parser to extract the entire body portion of an incoming request stream and expose it on req.body.

Pusher is also initialized with the app credentials and cluster from your dashboard. Make sure to update that, or else the Node server will have no connection to the dashboard. Lastly, the Node server will run on the 5000 port.

Next thing to do is define our app’s route and also add mock data for the expenses and income chart. Update your server.js file with the following.

let expensesList = {
    data: [
        {
            date: "April 15th 2017",
            expense: 100,
            income: 4000
        },
        {
            date: "April 22nd 2017",
            expense: 500,
            income: 2000
        },
        {
            date: "April 24th 2017",
            expense: 1000,
            income: 2300
        },
        {
            date: "April 29th 2017",
            expense: 2000,
            income: 1234
        },
        {
            date: "May 1st 2017",
            expense: 500,
            income: 4180
        },
        {
            date: "May 5th 2017",
            expense: 4000,
            income: 5000
        },
    ]
}

First, we have an expensesList object with the data containing expenses and income for particular days.

app.get('/finances', (req,res) => {

res.send(expensesList);

});

This route simply sends the expensesList object as JSON. We use this route to get the data and display on the frontend.

app.post('/expense/add', (req, res) => {
  let expense = Number(req.body.expense)
  let income = Number(req.body.income)
  let date = req.body.date;
  
  let newExpense  = {
    date: date,
    expense: expense,
    income: income
  };

  expensesList.data.push(newExpense);

  pusher.trigger('finance', 'new-expense', {
    newExpense: expensesList
  });

  res.send({
    success : true,
    income: income,
    expense: expense,
    date: date,
    data: expensesList
  })
});

The /expense/add route sure does a lot. It’s a POST route, which means we will be expecting some incoming data (in this case, expense amount and income amount).

We then push this new income and expense to the existing one, after which we also push the updated expensesList to Pusher.

Lastly, we send a JSON as a response to the route, containing the latest income, expense, date and updated expensesList.

Your final server.js should look like this:

const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const app = express();
const Pusher = require('pusher');

const pusher = new Pusher({
    appId: 'APP_ID',
    key: 'YOUR_KEY',
    secret: 'YOUR_SECRET',
    cluster: 'YOUR_CLUSTER',
    encrypted: true
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname + '/app')));

app.set('port', (process.env.PORT || 5000));

let expensesList = {
    data: [
        {
            date: "April 15th 2017",
            expense: 100,
            income: 4000
        },
        {
            date: "April 22nd 2017",
            expense: 500,
            income: 2000
        },
        {
            date: "April 24th 2017",
            expense: 1000,
            income: 2300
        },
        {
            date: "April 29th 2017",
            expense: 2000,
            income: 1234
        },
        {
            date: "May 1st 2017",
            expense: 500,
            income: 4180
        },
        {
            date: "May 5th 2017",
            expense: 4000,
            income: 5000
        },
    ]
}

app.get('/finances', (req,res) => {
    res.send(expensesList);
});

app.post('/expense/add', (req, res) => {
    let expense = Number(req.body.expense)
    let income = Number(req.body.income)
    let date = req.body.date;

    let newExpense  = {
        date: date,
        expense: expense,
        income: income
    };

    expensesList.data.push(newExpense);

    pusher.trigger('finance', 'new-expense', {
        newExpense: expensesList
    });

    res.send({
        success : true,
        income: income,
        expense: expense,
        date: date,
        data: expensesList
    })
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});

Building the Frontend (Vue + vue-chartjs)

Most of the frontend work will be done inside the src/components folder. Navigate to that directory and you should see a Hello.vue file. You can either delete that file or rename to Home.vue as we will be needing a Home.vue file inside the components folder.

Before we get started with building the chart and displaying it, there are a couple of things we need to do. Open up the App.vue file in the src folder and replace with the following code:

<template>
  <div id="app">
    <home></home>
  </div>
</template>

<script>
import Home from './components/Home' //We are importing the Home component
export default {
  name: 'app',
  components: {
    Home
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Next, we will install vue-chartjs, momentjs, pusher-js (Pusher’s Javascript library) and axios (We’ll use axios to make API requests). and then add them to the Vue.js app.

npm install axios vue-chartjs pusher-js moment

Once that’s done, we’ll import axios and register it globally in our app. We can do that by editing the main.js file in the src folder.

// src/main.js
import Vue from 'vue'
import App from './App'
import axios from 'axios' // we import axios from installed dependencies

Vue.config.productionTip = false

Vue.use(axios) // we register axios globally

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

Next, let’s create a Vue.js component that will help to display our chart. We are going to use this to specify what type of chart we want, configure its appearance and how it behaves.

We’ll then import this component into the Home.vue component and use it there. This is one of the advantages of vue-chartjs, it works by importing the base chart class, which we can then extend. Let’s go ahead and create that component. Create a new file called LineChart.vue inside the src/components folder, and edit with the code below.

<script>
  import {Line, mixins} from 'vue-chartjs' // We specify what type of chart we want from vue-chartjs and the mixins module
  const { reactiveProp } = mixins
  export default Line.extend({ //We are extending the base chart class as mentioned above
    mixins: [reactiveProp],
    data () {
      return {
        options: { //Chart.js options
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      // this.chartData is created in the mixin
      this.renderChart(this.chartData, this.options)
    }
  })
</script>

In the code block above, we imported the Line Chart from vue-chartjs and the mixins module. Chart.js ordinarily does not provide an option for an automatic update whenever a dataset changes but that can be done in vue-chartjs with the help of the following mixins:

  1. reactiveProp
  2. reactiveData

These mixins automatically create chartData as a prop or data and add a watcher. If data has changed, the chart will update. Read more here.

Also, the this.renderChart() function inside the mounted function is responsible for rendering the chart. this.chartData is an object containing the dataset needed for the chart and we’ll get that by including it as a prop in the Home.vue template, this.options contains the options object that determines the appearance and configuration of the chart.

We now have a LineChart component, but how can we see our chart and test its realtime functionality? We do that by adding the LineChart to our Home.vue component as well as subscribing to our Pusher channel via pusher-js.

Open up the Home.vue file and edit with the following:

<template>
  <div class="hello">
    <div class="container">
      <div class="row">
        <h2 class="title">Realtime Chart with Vue and Pusher</h2>
        <h3 class="subtitle">Expense and Income Tracker</h3>
        <!--We are using the LineChart component imported below in the script and also setting the chart-data prop to the datacollection object-->
        <line-chart :chart-data="datacollection"></line-chart>
      </div>
    </div>
    <div class="container">
      <div class="row">
        <form class="form" @submit.prevent="addExpenses">
          <h4>Add New Entry</h4>
          <div class="form-group">
            <label>Expenses</label>
            <input class="form-control" placeholder="How much did you spend?" type="number" v-model="expenseamount" required>
          </div>
          <div class="form-group">
            <label>Income</label>
            <input class="form-control" placeholder="How much did you earn?" type="number" v-model="incomeamount" required>
          </div>
          <div class="form-group">
            <label>Date</label>
            <input class="form-control" placeholder="Date" type="date" v-model="entrydate" required>
          </div>
          <div class="form-group">
            <button class="btn btn-primary">Add New Entry</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import moment from 'moment'
  import Pusher from 'pusher-js'
  import LineChart from '@/components/LineChart'
  const socket = new Pusher('APP_KEY', {
    cluster: 'eu',
    encrypted: true
  })
  const channel = socket.subscribe('finance')
  export default {
    name: 'home',
    components: {LineChart},
    data () {
      return {
        expense: null,
        income: null,
        date: null,
        expenseamount: null,
        incomeamount: null,
        datacollection: null,
        entrydate: null
      }
    },
    created () {
      this.fetchData()
      this.fillData()
    },
    mounted () {
      this.fillData()
    },
    methods: {
      fillData () {
      },
      addExpenses () {
      },
      fetchData () {
      }
    }
  }
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .title {
    text-align: center;
    margin-top: 40px;
  }
  .subtitle {
    text-align: center;
  }
  .form {
    max-width: 600px;
    width: 100%;
    margin: 20px auto 0 auto;
  }
  .form h4 {
    text-align: center;
    margin-bottom: 30px;
  }
  h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

fillData

This function gets called immediately the app is mounted and it basically makes an API request to the Node backend ( /finances) and retrieves the expensesList.

fillData () {
    axios.get('/finances')
      .then(response => {
        let results = response.data.data
    
        let dateresult = results.map(a => a.date)
        let expenseresult = results.map(a => a.expense)
        let incomeresult = results.map(a => a.income)
    
        this.expense = expenseresult
        this.income = incomeresult
        this.date = dateresult
    
        this.datacollection = {
          labels: this.date,
          datasets: [
            {
              label: 'Expense',
              backgroundColor: '#f87979',
              data: this.expense
            },
            {
              label: 'Income',
              backgroundColor: '#5bf8bf',
              data: this.income
            }
          ]
        }
      })
      .catch(error => {
        console.log(error)
      })
  }

A GET request is made to the /finances Node.js route which in turn returns the latest expensesList and we then manipulate that data with Javascript’s .map and assign it to various variables.

addExpenses

addExpenses () {
  //We first get the new entries via the v-model we defined on the income and expense input tag
  let expense = this.expenseamount
  let income = this.incomeamount
  let today = moment(this.entrydate).format('MMMM Do YYYY') //Formats the date via momentJS
  
  //Sends a POST request to /expense/new along with the expense, income and date.
  axios.post('/expense/add', {
      expense: expense,
      income: income,
      date: today
  })
    .then(response => {
      this.expenseamount = ''
      this.incomeamount = ''
      //We are bound to new-expense on Pusher and once it detects a change via the new entry we just submitted, we use it to build the Line Chart again.
      channel.bind('new-expense', function(data) {
          let results = data.newExpense.data
  
          let dateresult = results.map(a => a.date);
          let expenseresult = results.map(a => a.expense);
          let incomeresult = results.map(a => a.income);
          
          //The instance data are updated here with the latest data gotten from Pusher
          this.expense = expenseresult
          this.income = incomeresult
          this.date = dateresult
  
          //The Chart's dataset is updated with the latest data gotten from Pusher
          this.datacollection = {
              labels: this.date,
              datasets: [
                  {
                      label: 'Expense Charts',
                      backgroundColor: '#f87979',
                      data: this.expense
                  },
                  {
                      label: 'Income Charts',
                      backgroundColor: '#5bf8bf',
                      data: this.income
                  }
              ]
          }
      });
  })
}

The code block above simply utilizes a POST method route to /expense/add to update expensesList (Remember /expense/add route in the Node server sends the updated expensesList to the Pusher Dashboard) along with the income, expense and date data.

It then uses the data gotten from Pusher via channel.bind to build the Line Chart again and adds the new entry automatically to the Chart.

fetchData

This function gets called after the Vue instance is created and it also listens for changes to the Chart’s dataset via Pusher and automatically updates the Line Chart.

fetchData () {
   //We are bound to new-expense on Pusher and it listens for changes to the dataset so it can automatically rebuild the Line Chart in realtime.    
    channel.bind('new-expense', data => {
        let _results = data.newExpense.data
        let dateresult = _results.map(a => a.date);
        let expenseresult = _results.map(a => a.expense);
        let incomeresult = _results.map(a => a.income);
        
        //The instance data are updated here with the latest data gotten from Pusher
        this.expense = expenseresult
        this.income = incomeresult
        this.date = dateresult

        //The Chart's dataset is updated with the latest data gotten from Pusher
        this.datacollection = {
            labels: this.date,
            datasets: [
                {
                    label: 'Expense Charts',
                    backgroundColor: '#f87979',
                    data: this.expense
                },
                {
                    label: 'Income Charts',
                    backgroundColor: '#5bf8bf',
                    data: this.income
                }
            ]
        }
    });
}

Your final Home.vue file should look like this:

<template>
  <div class="hello">
    <div class="container">
      <div class="row">
        <h2 class="title">Realtime Chart with Vue and Pusher</h2>
        <h3 class="subtitle">Expense and Income Tracker</h3>
        <line-chart :chart-data="datacollection"></line-chart>
      </div>
    </div>
    <div class="container">
      <div class="row">
        <form class="form" @submit.prevent="addExpenses">
          <h4>Add New Entry</h4>
          <div class="form-group">
            <label>Expenses</label>
            <input class="form-control" placeholder="How much did you spend today?" type="number" v-model="expenseamount" required>
          </div>
          <div class="form-group">
            <label>Income</label>
            <input class="form-control" placeholder="How much did you earn today?" type="number" v-model="incomeamount" required>
          </div>
          <div class="form-group">
            <button class="btn btn-primary">Add New Entry</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import moment from 'moment'
  import Pusher from 'pusher-js'
  import LineChart from '@/components/LineChart'
  const socket = new Pusher('3e6b0e8f2442b34330b7', {
    cluster: 'eu',
    encrypted: true
  })
  const channel = socket.subscribe('finance')
  export default {
    name: 'home',
    components: {LineChart},
    data () {
      return {
        expense: null,
        income: null,
        date: null,
        expenseamount: null,
        incomeamount: null,
        datacollection: null
      }
    },
    created () {
      this.fetchData()
      this.fillData()
    },
    mounted () {
      this.fillData()
    },
    methods: {
      fillData () {
        axios.get('/finances')
          .then(response => {
            let results = response.data.data
            let dateresult = results.map(a => a.date)
            let expenseresult = results.map(a => a.expense)
            let incomeresult = results.map(a => a.income)
            this.expense = expenseresult
            this.income = incomeresult
            this.date = dateresult
            this.datacollection = {
              labels: this.date,
              datasets: [
                {
                  label: 'Expense',
                  backgroundColor: '#f87979',
                  data: this.expense
                },
                {
                  label: 'Income',
                  backgroundColor: '#5bf8bf',
                  data: this.income
                }
              ]
            }
          })
          .catch(error => {
            console.log(error)
          })
      },
      addExpenses () {
        let expense = this.expenseamount
        let income = this.incomeamount
        let today = moment().format('MMMM Do YYYY')
        axios.post('/expense/add', {
          expense: expense,
          income: income,
          date: today
        })
          .then(response => {
            this.expenseamount = ''
            this.incomeamount = ''
            channel.bind('new-expense', function (data) {
              let results = data.newExpense.data
              let dateresult = results.map(a => a.date)
              let expenseresult = results.map(a => a.expense)
              let incomeresult = results.map(a => a.income)
              this.expense = expenseresult
              this.income = incomeresult
              this.date = dateresult
              this.datacollection = {
                labels: this.date,
                datasets: [
                  {
                    label: 'Expense',
                    backgroundColor: 'transparent',
                    pointBorderColor: '#f87979',
                    data: this.expense
                  },
                  {
                    label: 'Income',
                    backgroundColor: 'transparent',
                    pointBorderColor: '#5bf8bf',
                    data: this.income
                  }
                ]
              }
            })
          })
          .catch(error => {
            console.log(error)
          })
      },
      fetchData () {
        channel.bind('new-expense', data => {
          let results = data.newExpense.data
          let dateresult = results.map(a => a.date)
          let expenseresult = results.map(a => a.expense)
          let incomeresult = results.map(a => a.income)
          this.expense = expenseresult
          this.income = incomeresult
          this.date = dateresult
          this.datacollection = {
            labels: this.date,
            datasets: [
              {
                label: 'Expense Charts',
                backgroundColor: '#f87979',
                data: this.expense
              },
              {
                label: 'Income Charts',
                backgroundColor: '#5bf8bf',
                data: this.income
              }
            ]
          }
        })
      }
    }
  }
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .title {
    text-align: center;
    margin-top: 40px;
  }
  .subtitle {
    text-align: center;
  }
  .form {
    max-width: 600px;
    width: 100%;
    margin: 20px auto 0 auto;
  }
  .form h4 {
    text-align: center;
    margin-bottom: 30px;
  }
  h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

One more thing!

Before we can run our app, we need to do something called API proxying. API proxying allows us to integrate our vue-cli app with a backend server (Node server in our case). This means we can run the dev server and the API backend side-by-side and let the dev server proxy all API requests to the actual backend.

We can enable API proxying by editing the dev.proxyTable option in config/index.js. You can edit with the code below.

proxyTable: {
  '/expense/add': {
    target: 'http://localhost:5000',
    changeOrigin: true
  },
  '/finances': {
    target: 'http://localhost:5000',
    changeOrigin: true
  },
}

After that has been done, we are finally ready to see our app and you can run npm run dev to start the app.

That’s it! At this point, you should have a realtime dashboard chart that updates in realtime.

You can check out the live demo here or go to the code for the whole app, which is hosted on Github for your perusal.

Conclusion

We’ve seen how to build a basic Line Chart with ChartJS in Vue with the help of vue-chartjs and also added realtime features thanks to Pusher.

Then we saw how to use reactiveProps to make ChartJS update its dataset if there’s been a change in the dataset. We also saw how to use Pusher to trigger events on the server and listen for them on the client side using JS.

Have you built anything cool with Pusher recently, a chart maybe? Let’s know in the responses below.

This post first appeared on the Pusher blog.

Discover and read more posts from Yomi Eluwande
get started