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
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.
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:
You’re going to need to install the following libraries:
npm i express --save
npm i node-fetch
npm i socket.io
npm i socket.io-client
npm i nodemon
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.
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).
**(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)**.
Web Hosting: The Best Hosting Solution For WordPress Sites in 2021.