Build a live news feed with React
You will need Node 6+ installed on your machine. Some knowledge of JavaScript and React will be helpful.
There are several instances where it’s important to show new updates in realtime. This could be in the form of displaying live activities for a sporting event, or updating a news feed with breaking news and headlines as they happen.
In this tutorial, we’ll explore how Pusher Channels can be used in conjunction with React to build a realtime news feed. If you want to play around with the code as you read this tutorial, visit this GitHub repository, which contains the final version of the code for you to check out and run locally.
Prerequisites
To follow along, a basic knowledge of JavaScript (ES6) and React is required. You also need to have the following installed on your machine:
Getting started
Start by creating a new empty directory news-app
and run npm init -y
from within it in order to initialize the project with a package.json
file.
Get News API credentials
Head over to News API and register for a free account. Once your account is created, your API key will be presented to you. Take note of it as we’ll be using it shortly.
Get Pusher credentials
Visit the Pusher website and create an account. Select Channels apps on the sidebar, and hit Create Channels app to create a new app. Once your app is created, check the API Keys tab to view your credentials.
In the root of your project directory, create a new file variables.env
and populate it with the following contents:
// variables.env
PORT=5000
NEWS_API_KEY=<your news api key>
PUSHER_APP_ID=<your app id>
PUSHER_APP_KEY=<your app key>
PUSHER_APP_SECRET=<your app secret>
PUSHER_APP_CLUSTER=<your app cluster>
Set up the React app
We will bootstrap our React application with create-react-app. Install it globally on your computer by running the following command:
npm install -g create-react-app
Once the installation process is done, you can run the command below within the news-app
directory to set up your React application:
create-react-app client
Once the command has finished running, cd
into the newly created client
folder and install the other dependencies we will be needing to build the app frontend.
npm install pusher-js pushid
The pusher-js
package is the client SDK for Pusher Channels, while pushid
helps us generate a random ID string which we’ll be needing when creating the news feed.
Run yarn start
to launch the development server once all the dependencies have been installed.
Application logic
Open up client/src/App.js
and change its contents to look like this:
// client/src/App.js
import React, { Component } from 'react';
import Pusher from 'pusher-js';
import pushid from 'pushid';
import './App.css';
class App extends Component {
state = {
newsItems: [],
}
componentDidMount() {
fetch('http://localhost:5000/live')
.then(response => response.json())
.then(articles => {
this.setState({
newsItems: [...this.state.newsItems, ...articles],
});
}).catch(error => console.log(error));
const pusher = new Pusher('<your app key>', {
cluster: '<your app cluster>',
encrypted: true,
});
const channel = pusher.subscribe('news-channel');
channel.bind('update-news', data => {
this.setState({
newsItems: [...data.articles, ...this.state.newsItems],
});
});
}
render() {
const NewsItem = (article, id) => (
<li key={id}><a href={`${article.url}`}>{article.title}</a></li>
);
const newsItems = this.state.newsItems.map(e => NewsItem(e, pushid()));
return (
<div className="App">
<h1 className="App-title">Live Bitcoin Feed</h1>
<ul className="news-items">{newsItems}</ul>
</div>
);
}
}
export default App;
Our application state
contains only one property: newsItems
, which will contain a list of all news articles. When the app loads, it will fetch a list of news items from the server and update the newsItems
array which would trigger an update on the page, causing a list of news items to be displayed.
We also subscribed the app to the news-channel
channel, which is where our server will publish events to. Once the update-news
event is received, the page will be updated with incoming news items.
Don’t forget to replace the <your app key>
and <your app cluster>
placeholders with the appropriate details from your Pusher account dashboard.
Add the application styles
Within the client
directory, locate src/App.css
and change its contents to look like this:
// client/src/App.css
.App {
width: 100%;
max-width: 700px;
margin: 0 auto;
}
.App-title {
text-align: center;
}
.text-input {
width: 100%;
border: 1px solid #f7f7f7;
padding: 10px;
}
.text-input:hover {
box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25);
}
.news-items {
list-style: none;
padding-left: 0;
}
.news-items li {
margin-bottom: 10px;
}
Set up the server
Let’s set up a simple Express server for the purpose of fetching news items from https://newsapi.org and triggering realtime updates with Pusher.
cd
to the root of the news-app
directory and install all the dependencies that are required to build the server:
npm install express cors dotenv newsapi pusher --save
Create a new server.js
file and open it up in your text editor. Add the following code to server.js
:
// server.js
require('dotenv').config({ path: 'variables.env' });
const express = require('express');
const cors = require('cors');
const Pusher = require('pusher');
const NewsAPI = require('newsapi');
const app = express();
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true,
});
const newsapi = new NewsAPI(process.env.NEWS_API_KEY);
const fetchNews = (searchTerm, pageNum) =>
newsapi.v2.everything({
q: searchTerm,
language: 'en',
page: pageNum,
pageSize: 5,
});
app.use(cors());
function updateFeed(topic) {
let counter = 2;
setInterval(() => {
fetchNews(topic, counter)
.then(response => {
pusher.trigger('news-channel', 'update-news', {
articles: response.articles,
});
counter += 1;
})
.catch(error => console.log(error));
}, 5000);
}
app.get('/live', (req, res) => {
const topic = 'bitcoin';
fetchNews(topic, 1)
.then(response => {
res.json(response.articles);
updateFeed(topic);
})
.catch(error => console.log(error));
});
app.set('port', process.env.PORT || 5000);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Once the /live
endpoint is hit, news articles about bitcoin are retrieved from newsapi.org, and sent back to the client. We then make further requests every five seconds with setInterval
and use Pusher to trigger the update-news
event with the incoming articles in the event payload.
Start the server by running node server.js
from the root of your project directory. At this point, you should have a news feed that updates in realtime.
Conclusion
In this tutorial, you have learned how to build a news feed with React and how to set up Channels for adding realtime functionality to the feed.
Thanks for reading! Remember that you can find the source code of this app in this GitHub repository.
1 October 2018
by Ayooluwa Isaiah