DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for [React] Real time updates data using Apexcharts - JSON API
Derick Zihalirwa
Derick Zihalirwa

Posted on

[React] Real time updates data using Apexcharts - JSON API

A guide on how to display live data fetched from a fake JSON API using React & react-apexcharts apexchart.

Many trading websites if not all, use an animated chart that displays real-time data for many use cases. In this tutorial, I will take you through how you can implement the same functionality in your React project.

Let's jump right in.

Prerequisite

  • A basic understanding of Reactjs, React hook, TailwindCSS, and JSON API.

  • Click here GitHub to clone the repo in your local machine. (follow the instruction in the .ReadMe file on how to run the application).

DEMO

Demo project
If you didn't clone the repo, check the link in the prerequisite.

βœ…We assume that your web app and server are running.

JSON SERVER PART
In our server directory, we have a file named data.json which is going to be our fake database.
as you can see it has an empty json object.
We will be adding data there later.

CLIENT PART
In web-client directory, inside src we have 2 folders Chart and FiciGame
Inside FiciGame, we have two more files, UpdateFici.js, and index.jsx and in Chart we have index.jsx
Inside UpdateFici.js we are going to create a function that will send random data to our 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' }
    })
}
Enter fullscreen mode Exit fullscreen mode

As you can see we are sending an object with time and a randomNumber, which will be used in the Chart component later.

Next, inside index.jsx we are going to 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) }
    }, [])
Enter fullscreen mode Exit fullscreen mode

The second, every 4 seconds, will be calling sendRandomData function we created early.

 useEffect(() => {
        const timer2 = setInterval(() => { sendRandomData() }, 4000);
        return () => { clearInterval(timer2) }
    }, [])
Enter fullscreen mode Exit fullscreen mode

Next we need to create the Chart where data will be displayed in real time. To do that let's go in index.jsx in our Chart folder and add this 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
Enter fullscreen mode Exit fullscreen mode

What does this snippet code do? Import the Chart component from react-apexcharts then calling it inside our ApexChart in which we are passing a parameter that is going to receive the data fetched from our fake API. the data returns an object (time and bid).

Then inside ApexChart component, we are mapping through data and passing bids in data and time in categories. (we used the ? to avoid any error in case the data is not available yet).

Last let import ApexChart in our FiciGame and pass the data received from our fake API.

import ApexChart from "../Chart";
...
 return (
        <ApexChart data={bidData} />
    )
Enter fullscreen mode Exit fullscreen mode

if everything works perfectly you can now refresh the page and check data.json file in the server repository, you will see, data get added automatically.

Result:

final Demo result
This is a perfect basic example of a simulation update of real-time data. You can adjust it in 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 will suggest you read more about WebSocket.

We've 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.

GitHub source code for this project.

if you want to customize your chart check apexcharts documentation.
any question? leave a comment below or chat with me on Twitter

Top comments (0)

πŸ€” Did you know?

Β 
DEV has a variety of tags to help you find the content you like. Find and follow your favorite tags.