A guide on how to display live data fetched from a fake JSON API using React & react-apexcharts apexchart.
In today's trading websites, animated charts that display real-time data are prevalent. In this tutorial, you will learn how to implement the same functionality in your React project using React and react-apexcharts apexchart.
Let's get started!
Prerequisite
You need to have a basic understanding of Reactjs, React hook, TailwindCSS, and JSON API.
You can clone the repo from GitHub by clicking here GitHub (follow the instructions in the .ReadMe file on how to run the application).
DEMO
If you didn't clone the repo, check the link in the prerequisite.
JSON SERVER PART
In the server directory, there is a file named data.json which will be your fake database.
As you can see, it has an empty JSON object. You will be adding data there late.
CLIENT PART
In the web-client directory, inside src, there are 2 folders Chart and FiciGame.
Inside FiciGame, there are two more files, UpdateFici.js, and index.jsx, and in Chart, there is index.jsx.
Inside UpdateFici.js, you will create a function that will send random data to your JSON server.
import moment from 'moment';
export const sendRandomData = async () => {
const currentDate = new Date();
const randNumber = Math.floor(Math.random() * 100);
const showDate = moment(currentDate).format('HH:mm:ss');
const doc = {
time: showDate,
bid: randNumber,
}
await fetch('http://localhost:7000/data', {
method: 'POST',
body: JSON.stringify(doc),
headers: { 'Content-Type': 'application/json' }
})
}
As you can see, you are sending an object with time and a randomNumber
, which will be used in the Chart component later.
Next, inside index.jsx
you will import sendRandomData
and create two functions. The first is going to call a fetch function inside a useEffect every 2 seconds (in millisecond => 2000) with the help of setIntervals
.
import {useEffect,useState} from "react";
import { sendRandomData } from "./UpdateFici";
// Fetch data from the fake API
const fetchFici = async () => {
const response = await fetch('http://localhost:7000/data')
console.log(response);
response.json().then(data => {
setBidData(data)
})
}
// Call the fetchFici function every 2 seconds
useEffect(() => {
const timer = setInterval(() => {
fetchFici()
}, 2000);
return () => { clearInterval(timer) }
}, [])
The second, every 4 seconds, will be calling sendRandomData
function we created early.
useEffect(() => {
const timer2 = setInterval(() => { sendRandomData() }, 4000);
return () => { clearInterval(timer2) }
}, [])
Next you need to create the Chart where data will be displayed in real time. To do that navigate to index.jsx and add the code below:
import React from 'react'
import Chart from "react-apexcharts";
const ApexChart = ({ data }) => {
return (
<div>
<Chart
type="area"
height={300}
width='100%'
series={[
{
name: "Commits",
data: data?.map(data => data.bid)
}
]}
options={{
chart: {
toolbar: {
show: false
},
},
colors: ['#f90000'],
stroke: { width: 1, curve: 'smooth' },
dataLabels: { enabled: false },
xaxis: {
categories: data?.map(data => data.time),
},
yaxis: {
show: false,
}
}}
/>
</div>
)
}
export default ApexChart
What does this code snippet do? It imports the Chart component from react-apexcharts and calls it inside your ApexChart, to which you pass a parameter that will receive the data fetched from your fake API. The data returns an object (time and bid).
Then inside the ApexChart component, you will map through data and pass bids in data and time in categories. (you will use the ?
to avoid any error in case the data is not available yet)..
Finally, let's import ApexChart in our FiciGame and pass the data received from our fake API.
import ApexChart from "../Chart";
...
return (
<ApexChart data={bidData} />
)
If everything works perfectly, you can now refresh the page and check the data.json file in the server repository. You will see that data is being added automatically.
Result:
This is a perfect basic example of a simulation update of real-time data. You can adjust it to your side-project as you like or make it much better.
side note📝
In your devTool, in the network tab, you will see requests are sent every 3 seconds. If you are planning to use an API that updates its data every second, I suggest you read more about WebSocket.
We have reached the end of our tutorial. I hope this gave you a good idea of how to integrate a real-time data update for your small project that uses apexcharts.
source code for this project: GitHub
If you want to customize your chart, check the apexcharts documentation.
Do you have any questions? Leave a comment below or chat with me on Twitter
Top comments (0)