Streams

Streamdata.io & Vue.js sample and step-by-step tutorial

Vue and Streamdata logo and man on mobile phone

featuredImage-new2View.js is one of the most famous JavaScript frameworks. It often appears in the top frameworks for web app development, and it turns out that someone in our team, (you can buy me with double chocolate cookies for a name) loves this framework.
So what did we do?

We decided to create a sample app to show how to use Streamdata.io in a Vue.js application! You won’t have any excuse after this not to take advantage of real-time data in the next app you’ll create.
Let’s see how to do this in a few steps.

1. Create project

First, let’s start with a simple Vue.js HelloWorld application. Vue.js comes with a cli that allows you to create an application with a single command line.

vue init webpack streamdataio-demo

This tool will ask a bunch of questions regarding your project configuration and create it with the appropriate structure and files.

As recommended by vue-cli, run npm install, and npm run dev in your freshly created directory in order to build and see the result in your browser.

2. Add dependencies

The first thing we’ll do is add Material Design and Bootstrap to our application, to style easily our simple UI.
To do so, run

npm install --save vue-material

Then, include the following link elements to the head section of index.html

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
<link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons">

Then, we need to add a few lines to the main.js file:

import VueMaterial from 'vue-material'
import 'vue-material/dist/vue-material.css'
Vue.use(VueMaterial);

To import Bootstrap, the process is the same.
Run

npm install --save bootstrap-vue

Import Bootstrap to your main.js:

import BootstrapVue from 'bootstrap-vue';
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.use(BootstrapVue);

This syntax uses the style-loader to load the styles. Style loader is another NPM module that has to be added:

npm install --save vue-style-loader

Finally, let’s add Streamdata.io SDK and JSON-patch dependencies by running

npm install --save streamdataio-js-sdk fast-json-patch

Our app dependencies are now ready. Let’s look at the project in more detail.

3. Edit source code

The project as created by vue-cli has the following structure:

project-structure

It is composed of a main component called App.vue, which represents the application, and a component Hello.vue which is the hello world sample for Vue.js.

Let’s create a new component and use it in the app.

3.1. Create StockMarket component

First create a Stockmarket.vue file in the component folder.

To use this new component in the application, we need to change the App.vue file:
add the import

import Stockmarket from './components/Stockmarket'

and add it to the components list.
By the way, while editing this file, take a few seconds to have a look at the template section, and notice that this is where the layout of the application is defined. You can take a few seconds to change the logo, and you’ll definitely need to add a stockmarket tag in order for your new component to be displayed in your app.

At the end, your App.vue file looks like this

<template>
 <div id="app">
   <img src="./assets/logo.png">
   <stockmarket></stockmarket>
 </div>
</template>

<script>
import Stockmarket from './components/Stockmarket'


export default {
 name: 'app',
 components: {
   Stockmarket
 }
}
</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>

Our app nutshell is now ready. Let’s work on the Stockmarket component.
A Vue.js component has three sections:

– template: defines the UI
– script: defines the logic
– style: defines… well… the style! 😉

3.2. Style

For the style, we’ll keep things simple, and copy-paste what is declared in the Hello component.

<style scoped>
h1, h2 {
 font-weight: normal;
}

ul {
 list-style-type: none;
 padding: 0;
}

li {
 display: inline-block;
 margin: 0 10px;
}

a {
 color: #42b983;
}
</style>

3.3. View

Then, we’ll prepare the UI to display data updated in real-time thanks to Streamdata. For this demo, we’ll use data coming from an API that emulates market data:

If you open this link in your favorite browser, you’ll see that this API returns data formatted as follows:

[  
   {  
      "title":"Microsoft",
      "company":"Microsoft Corporation",
      "ticker":"MSFT",
      "source":"ACME",
      "last":54.34,
      "dt":"2017-08-09T10:08:49.924",
      "volume":2.18E7
   },
   {  
      "title":"Alibaba",
      "company":"Alibaba Group Holding Ltd",
      "ticker":"BABA",
      "source":"ACME",
      "last":154.92,
      "dt":"2017-08-09T12:51:30.051",
      "volume":2.167E7
   },
<...>
]

So we’ll prepare the UI to display Title, Company, Ticker, Price, and Volume for each element in the array. We’ll show it in the table component provided by the material design library.

<div class="table">
   <md-table>
      <md-table-header>
         <md-table-row>
            <md-table-head>Title</md-table-head>
            <md-table-head>Company</md-table-head>
            <md-table-head>Ticker</md-table-head>
            <md-table-head>Price</md-table-head>
            <md-table-head>Volume</md-table-head>
         </md-table-row>
      </md-table-header>

      <md-table-body>
         <md-table-row v-for="(data, index) in tableData" :key="data.title">
            <md-table-cell>{{data.title}}</md-table-cell>
            <md-table-cell>{{data.company}}</md-table-cell>
            <md-table-cell>{{data.ticker}}</md-table-cell>
            <md-table-cell>{{data.last}}</md-table-cell>
            <md-table-cell>{{data.volume}}</md-table-cell>
         </md-table-row>
      </md-table-body>
   </md-table>
   <h5 style="text-align: right; font-style: italic;">Disclaimer: data is emulated and does not reflect the actual market data.</h5>
</div>

This table is ready to display data available in an object called tableData. Let’s see how we can build the object and keep it updated, using Streamdata.

3.4. Logic

In the script section, start by importing Streamdata.io SDK as follows:

import  {StreamDataIo} from 'streamdataio-js-sdk'

You’ll also need to import JSON-patch library to keep data up-to-date when receiving patches.

import * as jsonpatch from 'fast-json-patch'

We’ll create a Streamdata Event Source object as a global variable of the component and initialize it on component creation. This object has several callbacks that you need to implement:

wave: defines what to do when you get the first snapshot of data.
– onPatch: defines what to do when receiving an update (in the form of a JSON-Patch).
– onError: error handling callback.
– onOpen: commodity callback to show that the stream is opened.

After creating this object, don’t forget to open it when the component is created and close it when the component is destroyed.

The script section of our StockMarket component:

import { StreamDataIo } from 'streamdataio-js-sdk'
import * as jsonpatch from 'fast-json-patch'

export default {
   name: 'stockmarket',
   data() {
       return {
           streamData: null,
           tableData: []
       }
   },
   created: function () {
       this.streamData =
           StreamDataIo.createEventSource(
               'http://stockmarket.streamdata.io/v2/prices',
               'YOUR_STREAMDATA_TOKEN',
               []);

       this.streamData.onData(data => {
           // initialize your data with the initial snapshot
           console.log('Received data');
           this.tableData = data;
           console.table(this.tableData);
           
       }, this).onPatch(patch => {
           // update the data with the provided patch
           console.log('received patch %o', patch);
           jsonpatch.applyPatch(this.tableData, patch);
           console.table(this.tableData);
           
       }, this).onError(error => {
           // do whatever you need in case of error
           console.log('error: %o', error);
           
      },this).onOpen(() => {
         this.isConnected = true;
         // you can also add custom behavior when the stream is opened
         console.log('open');
       }, this);

       this.streamData.open();
   },
   destroyed: function () {
       this.streamData.close();
   }

}

Note that to create the Event Source object, you need to pass the URL of the API you want to stream and a Streamdata.io token. This one can be acquired for free by creating an account on our portal.

That’s it! You now have a Vue.js application that displays fake market data, updated in real-time thanks to Streamdata! Here is what it looks like.
vue.js and streamdata.io app with real-time data

I hope you enjoyed playing with our proxy and Vue.js..
You can find the source code of a complete StockMarket application in Vue.js on our GitHub. We’re now looking forward to hearing about the great things you’re going to build with all of this!
Happy coding!

Download the white paper to learn more about navigating the new streaming API landscape.

**Original source: streamdata.io blog