Add live comments in Gatsby

  • Christian Nwamba
June 12th, 2018
You will need Node and npm or Yarn installed on your machine. A basic understanding of JavaScript will be helpful.

According to Wikipedia, a static web page (sometimes called a flat page/stationary page) is a web page that is delivered to the user exactly as stored, in contrast to dynamic web pages which are generated by a web application

Gatsby is a modern static site generator that allows you to build static web pages using React and GraphQl. Getting started with Gatsby is pretty easy and its installation is an npm install or yarn install away.

Today we’ll be adding a realtime comment section to the sports blog we’ll be building. We’ll call our blog the “Football transfer buzz with Gordon Mc-gossip”. Our application will contain a post and allow users to leave comments and everyone gets to see it in realtime.

Prerequisites

  1. Kindly ensure you have Node, Npm or Yarn installed on your machine before moving past this section. This will be needed for running and managing the dependencies needed by our application.
  2. Also, no knowledge of React is required, but a basic understanding of JavaScript may be helpful.
  3. Pusher: this is a framework that allows you to build realtime applications with its easy to use pub/sub messaging API.
  4. Gatsby: this is a static site generator. ( minimum version "gatsby": "^1.9.247")

Install Gatsby

Installing Gatsby is pretty easy once you have Node installed on your machine. Simply run:

    # for npm users
    npm i -g gatsby-cli
    # for yarn users
    yarn global add gatsby-cli

This Gatsby CLI comes with a few helpful commands that can help you build and test your apps locally.

Create your app

To create our project, simply run:

    # new gatsby project
    gatsby new gatsby-site-pusher

This will create our new project Transfer-Buzz and install its dependencies. If you cd into your new project directory, it will look like this.

Most of the work we’ll be doing would be in the src/ directory. The components we’ll create would go into the src/components directory and pages would go into the src/pages directory.

Install dependency:

    # for npm users
    npm i --save pusher-js
    # for yarn users
    yarn add pusher-js

Get our Pusher credentials

If you don't have a Pusher account already, kindly create one here. Once you have an account, simply head down to your dashboard and create an app. Once that is done, click on App Keys and note your credentials. We'll be needing them in a bit.

Creating our app components

The first component we’ll create is our CommentList component. This will be responsible for listing the comments left by users.

    // src/components/comment-list.js

    import React from 'react'

    export default ({comments}) => {
      comments = comments.map((comment, i) => (
        <div key={i} style={{
          padding: '5px',
          border: '1px solid grey'
        }}>
          <p><strong>{comment.author}:</strong></p>
          <p>{comment.message}</p>
        </div>
      ))
      return (
        <section>
          <strong>Comments: </strong>{comments}
        </section>
      )
    }

This simply takes an array of comments with attributes {author, message} and returns a CommentList component.

Next, is the Comment component, which will have a form for accepting new comments and list comments below.

    // src/components/comment.js
    import React, { Component } from 'react'
    import CommentList from './comment-list'
    import Pusher from 'pusher-js'

    /**
    * initialize pusher with your credentials.
    * Get 'key' from pusher dashboard
    */
    const pusher = new Pusher('key', {
      cluster: 'eu',
      encrypted: true
    })

    // subscribe your pusher instance to the channel 'sport-buzz-news'
    const channel = pusher.subscribe('sport-buzz-news')

    /* global fetch */
    export default class Comment extends Component {
      constructor (props) {
        super(props)
        this.state = {
          comments: [],
          author: '',
          message: ''
        }
      }

    /**
    * This will load components from the server on app startup,
    * and also subscribe our app to listen for updates
    */
      async componentDidMount () {
        const comments = await fetch('http://localhost:8080/comments').then(res => res.json())
        this.setState({comments: [...comments, ...this.state.comments]})
        this.receiveUpdateFromPusher()
      }

      componentWillUnmount () {
        pusher.unsubscribe('sport-buzz-news')
      }

      /**
      * add new comments to the top of the list
      * once there's an update
      */
      receiveUpdateFromPusher () {
        channel.bind('new-comment', comment => {
          this.setState({
            comments: [comment, ...this.state.comments]
          })
        })
        console.log('app subscription to event successful')
      }

      handleChange (type, event) {
        if (type === 'author') {
          this.setState({author: event.target.value})
          return
        }
        if (type === 'message') {
          this.setState({message: event.target.value})
        }
      }

      /**
      * post comment to the server
      */
      async postComment (author, message) {
        await fetch('http://localhost:8080/comment', {
          body: JSON.stringify({author, message}),
          method: 'POST',
          headers: {
            'user-agent': 'Mozilla/4.0 ',
            'content-type': 'application/json'
          }
        })
      }

      handleSubmit (event) {
        event.preventDefault()
        this.postComment(this.state.author, this.state.message)
        this.setState({author: '', message: ''})
      }

      render () {
        return (
          <div>
            <form onSubmit={this.handleSubmit.bind(this)}>
              <label>
              Name:
                <input type='text' value={this.state.author} onChange={this.handleChange.bind(this, 'author')} />
              </label>
              <label>
                <br />
              Message:
                <textarea type='text' value={this.state.message} onChange={this.handleChange.bind(this, 'message')} />
              </label>
              <br />
              <input type='submit' value='Submit' />
            </form>
            <CommentList comments={this.state.comments} />
          </div>
        )
      }
    }

Here, when the component gets mounted, we try to load previous comments from the server and pass that data as props to the CommentList component.

Note: please remember to updated placeholders with your pusher credentials.

Putting content on our page

Open your src/pages/index.js file which should already exist. You should replace its content with this:

    // src/pages/index.js

    import React from 'react'
    import Comment from '../components/comment'

    const IndexPage = () => (
      <div>
        <h1>Leroy Aziz Sané left out of German squad for the world cup</h1>
        <p>
          A lot of talks is currently ongoing about the Manchester City winger Leroy Sane being left out of the German team.
          He was a prolific player this season with Mancity winning the premier league andthe significant contribution he brought to the team in front of Goal.
          The decision by the German coach, Low to leave him out of the squad list was totally unexpected. Football really is a funny sport.
        </p>
        <p>
          Let me know your thoughts in the comment section below
        </p>
        <Comment />
      </div>
    )

    export default IndexPage

This contains a post we made and the Comment component we imported above.

Getting data in Gatsby

Gatsby uses GraphQL for getting data. It could be from any source. There are a few files where changes need to be made to get data. We have gatsby-node.js, gatsby-browser.js, gatsby-config.js among others.

What we’re concerned about right now is gatsby-config.js. It is responsible for passing data down to our src/components/header.js component. This gets data locally from the file and it’s an easy way to initialize your application with data.

Open up your src/components/header.js file and you should see this:

    // src/components/header.js

    import React from 'react'
    import Link from 'gatsby-link'

    const Header = ({ siteTitle }) => (
      <div
        style={{
          background: 'rebeccapurple',
          marginBottom: '1.45rem'
        }}
      >
        <div
          style={{
            margin: '0 auto',
            maxWidth: 960,
            padding: '1.45rem 1.0875rem'
          }}
        >
          <h1 style={{ margin: 0 }}>
            <Link
              to='/'
              style={{
                color: 'white',
                textDecoration: 'none'
              }}
            >
              {siteTitle}
            </Link>
          </h1>
        </div>
      </div>
    )

    export default Header

It takes a prop called siteTitle which was exported from the file gatsby-config.js.

Feel free to go ahead and change the value for title in gatsby.js to Football transfer buzz with Gordon Mc-Gossip'.

Setting up the server

Comments sent by users need to go somewhere, that’s what the server is for. It will save the comment, and publish it to Pusher who will trigger an update to all clients subscribed to that channel and listening for that event.

First, we’ll need to add the dependencies needed by our server.

    # for yarn users
    yarn add express body-parser cors pusher
    # for npm users
    npm i express body-parser cors pusher

Create the file server.js and add the following:

    // server.js
    const express = require('express')
    const app = express()
    const bodyParser = require('body-parser')
    const cors = require('cors')
    const Pusher = require('pusher')

    app.use(cors())
    app.use(bodyParser.urlencoded({ extended: true }))
    app.use(bodyParser.json())

    const port = process.env.PORT || 8080

    const pusher = new Pusher({
      appId: 'appId',
      key: 'key',
      secret: 'secret',
      cluster: 'eu',
      encrypted: true
    })

    let comments = [
      {
        author: 'robo',
        message: 'i totally didn\'t see that coming'
      }
    ]

    /**
    * receive new comment from the client
    * update the comments array with the new entry
    * publish update to Pusher
    */
    app.post('/comment', function (req, res) {
      const {author, message} = req.body
      comments = [...[{author, message}], ...comments]
      pusher.trigger('sport-buzz-news', 'new-comment', {author, message})
      res.sendStatus(200)
    })

    // send all comments to the requester
    app.get('/comments', function (req, res) {
      res.json(comments)
    })

    app.listen(port, function () {
      console.log('Node app is running at localhost:' + port)
    })

Here, we initialize Pusher with our credentials gotten from our dashboard. When we get a request on localhost:8080/comments we return all comments gotten so far and receive comments sent to POST localhost:8080/comment.

Running the app

We’ll use one of Gatsby’s helpful CLI commands to start our application. Simply run:

    # gatsby cli command
    gatsby develop

This will start our application on port 8000 and can be accessed here http://localhost:8000/.

You’ll also need to start the server by running:

    # start node server
    node server.js

Our server application will run on http://localhost:8080/ and all API calls would go here.

More

Gatsby allows you to export as a static content when going to production. It could prefetch your data from any data source and bundle it into the generated static file.

To do that, simply run:

    # make production build
    gatsby build

Gatsby will perform an optimized production build for your site generating static HTML and per-route JavaScript code bundles.

Conclusion

We’ve been able to build a simple blog application with a live comment section. This was done using Pusher and Gatsby. The repo for this tutorial lives here. Feel free to contribute.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.