Sunday, 23 April 2017

Push data from Socket.io to Vue data

On the server side, I'm just catching the tweets. Each time I get new tweet, I would like to add it to Vue data.

index.js:

// require Express and Socket.io
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var config = require('./config.js');
var Twit = require('twit');

var T = new Twit({
  consumer_key:         config.TWITTER.CONSUMERKEY,
  consumer_secret:      config.TWITTER.CONSUMERSECRET,
  access_token:         config.TWITTER.ACCESSTOKEN,
  access_token_secret:  config.TWITTER.ACCESSTOKENSECRET,
  timeout_ms:           config.TWITTER.TIMEOUT,
});

var visitorsData = {};

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

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'views/index.html'));
});

http.listen(app.get('port'), function() {
  console.log('listening on *:' + app.get('port'));
});

// getting tweets 
var stream = T.stream('statuses/filter', { track: 'mango' })
stream.on('tweet', function (tweet) {
    io.sockets.emit('tweet', tweet);
    console.log(tweet.text);
})

and index.html looks like this:

<!DOCTYPE html>
<html>
<head>
  <title>Latest tweet</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <ul>
      <li>
        The latest tweet
        <p></p>
      </li>
    </ul>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        twitText: 'There should go twit text meesage from stream'
      }
    })
  </script>
</body>

I thought that io.sockets.emit('tweet', tweet); will help me achieve that, but I'm totally not sure what to do with it.



via Moo

No comments:

Post a Comment