paint-brush
Build a realtime chart with Vue.jsby@Yomi
11,605 reads
11,605 reads

Build a realtime chart with Vue.js

by Yomi EluwandeMarch 16th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<a href="https://hackernoon.com/tagged/data" target="_blank">Data</a> 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.

Company Mentioned

Mention Thumbnail
featured image - Build a realtime chart with Vue.js
Yomi Eluwande HackerNoon profile picture

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.

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.

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.

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:

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:

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 opening the main.js file in the src folder.

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.

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:

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.

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

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.

Your final Home.vue file should look like this:

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.

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.