Build a realtime table with Next.js

Introduction

Realtime applications are generally applications that produce time sensitive data or updates that requires immediate attention or consumption. From flight management software to following up with the score line and commentary when your favorite football team is playing.

We’ll be building a realtime application that will show live updates on reviews about the next movie users want to watch at the cinema. All that juicy reviews from fans, viewers and critics around the world, and I’ll want them in real time. Let’s call it Rotten pepper.

realtime-tables-next-demo

The application will contain a form that allows users to fill in their review easily and will also display a table showing reviews left by users world wide in realtime. This part of the application will be built with Next.js

The other important part of this application is the API, where reviews posted by the user will go to. We’ll build this using Express and Node. Pusher would be the glue that sticks both ends together.

Prerequisites

We’ll be using the following tools to help build this quickly.

  • Next.js: this is a framework for producing server rendered applications. Just as you would with PHP, but this time with React.
  • Pusher: this is a framework that allows you to build realtime applications with its easy to use pub/sub messaging API.
  • React Table: this is a lightweight table built for React for showing extensive data.

Please ensure you have Node and npm installed before starting the tutorial. No knowledge of React is required, but a basic understanding of JavaScript may be helpful.

Let’s get building.

App structure

If you have no idea about Next.js, I recommend you take a look here. It’s pretty easy and in less than an hour, you’ll be able to build real applications using it.

Let’s create the directory where our app will sit:

1# make directory and cd into it
2    mkdir movie-listing-next && cd movie-listing-next
3    
4    # make pages, components and css directory
5    mkdir pages
6    mkdir components
7    mkdir css

Now we can go ahead to install dependencies needed by our application. I’ll be using Yarn for my dependency management, but feel free to use npm also.

Install dependencies using Yarn:

1# initilize project with yarn
2    yarn init -y
3    
4    # add dependencies with yarn
5    yarn add @zeit/next-css axios next pusher-js react react-dom react-table

Let’s add the following to the script field in our package.json and save. This makes running commands for our app more easier.

1// package.json
2    {
3      "scripts": {
4        "dev": "next",
5        "server": "node server.js"
6       }
7    }

For users to submit their reviews, they’ll need a form where they can input their name, review and rating. This is a snippet from [components/form.js](https://github.com/Robophil/movie-listing-next/blob/master/components/form.js) , which is a simple React form that takes the name, review and rating. You’ll need to create yours in the components directory.

Snippets from [components/form.js](https://github.com/Robophil/movie-listing-next/blob/master/components/form.js):

1export default class Form extends React.Component {
2    ....
3      render () {
4        return (
5          <form onSubmit={this.handleSubmit}>
6            <div>
7              <label>
8              Name:
9              <br />
10                <input type='text' value={this.state.name} onChange={this.handleChange.bind(this, 'name')} />
11              </label>
12            </div>
13    
14            <div>
15              <label>
16              Review:
17              <br />
18                <textarea rows='4' cols='50' type='text' value={this.state.review} onChange={this.handleChange.bind(this, 'review')} />
19              </label>
20            </div>
21    
22            <div>
23              <label>
24              Rating:
25              <br />
26                <input type='text' value={this.state.rating} onChange={this.handleChange.bind(this, 'rating')} />
27              </label>
28            </div>
29            <input type='submit' value='Submit' />
30          </form>
31        )
32      }
33    }

If you’re a React developer, you should feel right at home here. On form submission, the data is being passed down to this.props.handleFormSubmit(this.state). This props is passed down from a different component as we’ll soon see.

Now we have our form, but we still need a page to list all the reviews submitted by users. The size of our reviews could grow rapidly and we still want this in realtime, so it’s best to consider pagination from the outset. That’s why we’ll be using react-table, as highlighted above this is lightweight and will give us pagination out of the box.

The snippet below is from our index page, which you’ll need to create here [pages/index.js](https://github.com/Robophil/movie-listing-next/blob/master/pages/index.js) .

1// pages/index.js
2    import React from 'react'
3    import axios from 'axios'
4    import ReactTable from 'react-table'
5    import 'react-table/react-table.css'
6    import '../css/table.css'
7    import Form from '../components/form'
8    import Pusher from 'pusher-js'

Here we import our dependencies which include axios for making http calls, our styles from table.css and the form component we created earlier on.

1// pages/index.js
2    const columns = [
3      {
4        Header: 'Name',
5        accessor: 'name'
6      },
7      {
8        Header: 'Review',
9        accessor: 'review'
10      },
11      {
12        Header: 'Rating',
13        accessor: 'rating'
14      }
15    ]
16    const data = [
17      {
18        name: 'Stan Lee',
19        review: 'This movie was awesome',
20        rating: '9.5'
21      }
22    ]

React-table, which is pretty easy to set up needs a data and columns props to work. There’s a pretty easy example here if you want to learn more. We’re adding a sample review to data to have at least one review when we start our app.

1// pages/index.js
2    const pusher = new Pusher('app-key', {
3      cluster: 'cluster-location',
4      encrypted: true
5    })
6    
7    const channel = pusher.subscribe('rotten-pepper')
8    
9    export default class Index extends React.Component {
10      constructor (props) {
11        super(props)
12        this.state = {
13          data: data
14        }
15      }
16    
17      render () {
18        return (
19          <div>
20            <h1>Rotten <strike>tomatoes</strike> pepper</h1>
21            <strong>Movie: Infinity wars </strong>
22            <Form handleFormSubmit={this.handleFormSubmit.bind(this)} />
23            <ReactTable
24              data={this.state.data}
25              columns={columns}
26              defaultPageSize={10}
27        />
28          </div>
29        )
30      }
31    }

Here, we created our React component and initialize Pusher and subscribe to the rotten-pepper channel. Kindly get your app-id from your Pusher dashboard and if you don’t have an account, kindly create one here. The state value this.data is initialized with the sample data created above and our render method renders both or form and our table.

At this point, we’re still missing a few vital parts. Pusher has been initialized, but it’s currently not pulling any new reviews and updating our table.

To fix that, add the following to your react component in pages/index.js

1// pages/index.js
2    componentDidMount () {
3        this.receiveUpdateFromPusher()
4      }
5    
6      receiveUpdateFromPusher () {
7        channel.bind('new-movie-review', data => {
8          this.setState({
9            data: [...this.state.data, data]
10          })
11        })
12      }
13    
14      handleFormSubmit (data) {
15        axios.post('http://localhost:8080/add-review', data)
16        .then(res => {
17          console.log('received by server')
18        })
19        .catch(error => {
20          throw error
21        })
22      }

In componentDidMount, we’re calling the method receiveUpdateFromPusher which would receive new reviews submitted by users and update our table. We’re calling receiveUpdateFromPusher in componentDidMount so this only get called once. The handleFormSubmit method is responsible for sending the review submitted by users down to your endpoint. This is passed as a props to the the form component as mentioned before.

1// next.config.js
2    const withCSS = require('@zeit/next-css')
3    module.exports = withCSS()

This should be placed in a file called next.config.js in your root directory movie-listing-next. It’s responsible for loading all .css files which contains our styles on app startup.

Now that our app can load .css properly, create the file css/form.css which is needed by components/form.js to style our app’s form:

1form {
2      margin: 30px 0;
3    }
4    
5    form div {
6      margin: 10px 0;
7    }

To keep the content of our review table center aligned, create the file css/table.css and add the following style snippet.

1.rt-td {
2      text-align: center;
3    }

To set the root structure of our app, we create pages/_document.js. This is where the rest of our app will sit.

1// pages/_document.js
2    import Document, { Head, Main, NextScript } from 'next/document'
3    
4    export default class MyDocument extends Document {
5      render () {
6        return (
7          <html>
8            <Head>
9              <title>Movie listing</title>
10              <link rel='stylesheet' href='/_next/static/style.css' />
11            </Head>
12            <body>
13              <Main />
14              <NextScript />
15            </body>
16          </html>
17        )
18      }
19    }

Now, let’s setup the endpoint where all reviews submitted will be received.

Rotten pepper endpoint

This is where all the magic happens. When a review gets submitted, we’ll want other users to be aware of the new data and this is where Pusher shines. Create a file server.js at the root of your application and add the following snippet as it’s content. Remember to visit your Pusher dashboard to get your appId, appKey, appSecret.

1// server.js
2    const pusher = new Pusher({
3      appId: 'appId',
4      key: 'appKey',
5      secret: 'appSecret',
6      cluster: 'cluster',
7      encrypted: true
8    })
9    
10    app.post('/add-review', function (req, res) {
11      pusher.trigger('rotten-pepper', 'new-movie-review', req.body)
12      res.sendStatus(200)
13    })

From above, once the user hits /add-review we trigger an event new-movie-review with pusher which clients are currently listening on. We pass it the new review that was submitted and the connected clients update themselves.

The values for appId, appSecret and appKey should be replaced with actual credentials. This can be gotten from your app dashboard on Pusher, and if you don’t have an account simply head down to https://pusher.com/ and create an account.

realtime-table-nest-keys

Let’s add dependencies need by our app:

1# add dependencies needed by server.js
2    yarn add body-parser cors express pusher

At this point, the dependencies field in our package.json should contain the following below:

1"dependencies": {
2        "@zeit/next-css": "^0.1.5",
3        "axios": "^0.18.0",
4        "body-parser": "^1.18.2",
5        "cors": "^2.8.4",
6        "express": "^4.16.3",
7        "next": "^5.1.0",
8        "pusher": "^1.5.1",
9        "pusher-js": "^4.2.2",
10        "react": "^16.3.2",
11        "react-dom": "^16.3.2",
12        "react-table": "^6.8.2"
13      }

if not, simply replace the contents of the dependencies field in your package.json and run

1# install dependencies from package.json
2    yarn

The entire content of server.js is right below. The line const port = process.env.PORT || 8080 simply picks up the preferred port to run our app and app.listen(port, function () {} starts our app on that port.

1// server.js
2    const express = require('express')
3    const app = express()
4    const bodyParser = require('body-parser')
5    const cors = require('cors')
6    const Pusher = require('pusher')
7    
8    app.use(cors())
9    app.use(bodyParser.urlencoded({ extended: true }))
10    app.use(bodyParser.json())
11    
12    const port = process.env.PORT || 8080
13    
14    const pusher = new Pusher({
15      appId: 'appId',
16      key: 'appKey',
17      secret: 'appSecret',
18      cluster: 'cluster',
19      encrypted: true
20    })
21    app.post('/add-review', function (req, res) {
22      pusher.trigger('rotten-pepper', 'new-movie-review', req.body)
23      res.sendStatus(200)
24    })
25    
26    app.listen(port, function () {
27      console.log('Node app is running at localhost:' + port)
28    })

Now let’s see if what we’ve done so far works.

In one bash window:

1# start next app
2    yarn run dev

and for our endpoint simply run in a new bash window:

1# start api server
2    yarn run server

You can open [http://localhost:3000](http://localhost:3000) in as many tabs as possible and see if a review posted in one tab gets to the others.

Conclusion

Building a realtime application can be super easy with the right tools. Pusher takes all that socket and connection work out of the way and allow us focus on the app we’re building. Now I can sit back and watch reviews come :-)

The repo where this was done can be found here. Feel free to fork and improve. Obviously this needs some more styling. How do you think we could improve this more?

Happy hacking!!