Setting up Socket.io with Express JS and React to get real time data

Wednesday May 26, 2021

So you’re building something that requires real-time data with React JS— Socket.io to the rescue. We’ll get over some of the setup hurdles so you can continue building your master-piece… in peace.

Hashtag React JS.

I’ll keep this short and simple.

Let’s take this scenario for example. You’re building a React app that tracks Earthquakes in real-time. The app is to have a map section and a table-feed section which couple together to show updated earthquakes every hour around the globe.

So you decide to use React JS for the UI, Express for the server and you need some tool to help you get the earthquake data from your fetch call inside your server.js file to your front-end, so you can display them inside your map and table-feed.

You COULD do a post / get from your server to the client/front-end, but that would get messy with time and is totally unscalable, specially if you want some sort of bi-directional, real-time data flow. So you decide to go with Socket.io because it allows exactly that.

Now let’s get to the actual setup:

Cut away all the fluff in our React JS setup and we see that we have only 2 files that we are working with to get this up and running: server.js and feed.js

You’re going to need to install the following libraries:

  1. Express JS: npm i express --save
  2. Node-Fetch: npm i node-fetch
  3. Socket.io: npm i socket.io
  4. Socket.io Client: npm i socket.io-client
  5. Nodemon: npm i nodemon

Lets take a look at our server.js :

We initiate an io connection, inside which we make our fetch call. Now, inside our fetch, is where the socket magic happens. We define a custom event called latest_quakes and emit it — attaching our earthquake JSON data.

And now, lets look at our feed.js :

Pretty self-explanatory…

Let’s start up our server-file (i’m using nodemon) by entering the following command in our terminal at the root level: nodemon server.js . (The server.js is located at the root level).

Now, you should see the following JSON data inside your browser console:

 
React JS getting JSON back from API
Screenshot belongs to author

And THATS IT! Enjoy 🙂

Resources:

**(Disclosure: This article contains affiliate links for which I might receive a small commission from BlueHost, at no extra cost to you if you choose to purchase through my links)**.

Gist: https://gist.github.com/pjcodesjs

Web Hosting: The Best Hosting Solution For WordPress Sites in 2021.