Using ChartJS and React hooks to create a line chart related to an API
By: Luann Sapucaia
Tags: Axios, React, Charts, JavaScript, API

Using ChartJS and React hooks to create a line chart related to an API Luann Sapucaia Jun 8, 2020·5 min read

I’ve been spending my free time trying to get a better understanding of React, and if you have done the same recently, you know that the react hooks are coming to stay.

Even knowing that the classes are not supposed to be extinguished from the framework, most developers are starting to adopt the concept of using hooks to reduce the need to restructure your components and make them easier to understand.

“With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.”

Although react hooks are quite popular among the developers, sometimes it’s hard to find tools that are designed to work in this way. In this tutorial, I’ll give you a guide to creating your React-based application using hooks instead of classes. We’ll be creating a chart with daily Covid-19 confirmed cases in Brazil.

Creating the project

First of all, we have to create a react project and enter its folder:

yarn create react-app medium-chart

cd medium-chart

The second step is to add the libs to both connect to the API and to use the charts:

npm i --save chart.js

npm i --save react-chartjs-2

yarn add axios

//aparently there's no yarn command to install the react chartjs-2

Axios JS

Now we’re good to go. To start the creation of this example, we’ll be using the Covid-19 API through AXIOS. That said, create a file called API.js with the following code:

import axios from 'axios';

baseURL: '

}) const api = axios.create({baseURL: ' https://api.covid19api.com' }) export default api;

Creating the component

Note that we don’t have to import React on it because this part only involves JavaScript. That file will be imported into our component but in a different file. We must create a new file called Chart.js . Inside of it, it’s important to import React , the const api we created, the beloved hooks useEffect and useState , the component of the chart we’ll be using ( Line ), and a style’s file.

import React from 'react';

import api from '../../assets/API';

import { useEffect, useState } from 'react';

import { Line } from 'react-chartjs-2';

import './chart.css';

The first info we want to add into our component is the state and the update state function, and both come from the state hook useState :

export default function ChartTest() {

const [dataChart, setDataChart] = useState ({});

}

In order to fetch the data from the API, we have to use the useEffect hook. Remember, we can’t create async functions directly from this state. Instead, we have to create an async function inside of it:

export default function ChartTest() {

const [ dataChart, setDataChart ] = useState ( {} ); useEffect(() => {

const fetchData = async () => {

await api.get('dayone/country/brazil/status/confirmed')

.then ( response => {

for ( dataObj of response.data ) {

console.log( dataObj )

}

});

}, []);

}

Note that the response from this get request is an array of objects. That said, in order to show all the elements of its array in the chart, we have to go through all of the elements. The for loop does this like it’s been shown above.

Here’s an example of the object inside of the array’s response:

{

“Country”: “Brazil”,

“CountryCode”: “BR”,

“Province”: “”,

“City”: “”,

“CityCode”: “”,

“Lat”: “-14.24”,

“Lon”: “-51.93”,

“Cases”: 1,

“Status”: “confirmed”,

“Date”: “2020–02–26T00:00:00Z”

}

Next, we can create arrays to insert the info that we want to see. That way, we only manipulate the info we want. In this case, we’ll need a relation between the confirmed cases (an integer number)and the days of the year (a date), and push the loop’s info into them:

export default function ChartTest() {

const [ dataChart, setDataChart ] = useState ( {} ); useEffect(() => {

const fetchData = async () => {

let confirmedCases = [];

let dateOfCases = [];

await api.get('dayone/country/brazil/status/confirmed')

.then ( response => {

for ( let dataObj of response.data ) {

confirmedCases.push(parseInt(dataObj.Cases));

let tempDate = new Date (dataObj.Date);

dateOfCases.push(tempDate.getUTCDate()); //in order to get better visualization of the chart,

//the getUTCDate was used to reduce the number of info

//shown under the chart.

}

});

}, []);

}

We’re almost done finishing our component. Now we just have to put the info we filtered inside of the dataChart state through setDataChart using the info of the chartJS documentation.

export default function ChartTest() {

const [ dataChart, setDataChart ] = useState ( {} ); useEffect(() => {

const fetchData = async () => {

let confirmedCases = [];

let dateOfCases = [];

await api.get('dayone/country/brazil/status/confirmed')

.then ( response => {

for ( let dataObj of response.data ) {

confirmedCases.push(parseInt(dataObj.Cases));

let tempDate = new Date (dataObj.Date);

dateOfCases.push(tempDate.getUTCDate());

}

});

setDataChart({

labels: dateOfCases,

datasets: [{

label: 'Confirmed cases',

data: confirmedCases

}]

});

}, []);

}

Since we only created the fetchData function, we have to call it inside of the useEffect hook. Last, we just need to call the Line component inside of the ChartTest return:

export default function ChartTest() {

const [ dataChart, setDataChart ] = useState ( {} ); useEffect(() => {

const fetchData = async () => {

let confirmedCases = [];

let dateOfCases = [];

await api.get('dayone/country/brazil/status/confirmed')

.then ( response => {

for ( let dataObj of response.data ) {

confirmedCases.push(parseInt(dataObj.Cases));

let tempDate = new Date (dataObj.Date);

dateOfCases.push(tempDate.getUTCDate());

}

});

setDataChart({

labels: dateOfCases,

datasets: [{

label: 'Confirmed cases',

data: confirmedCases

}]

});

fetchData();

}, []);

return(

<div className='container'>

<Line data={ dataChart }/>

</div>

)

}

To get a better visualization of the chart, I added the following CSS code to the container class:

.container {

margin: 0 auto;

max-width: 960px;

}

Calling the component in the App

In the final step, we’ll call the component we created to the App component, where it will be visible:

import React from 'react';

import './App.css';

import ChartTest from './chart/Chart.js'; function App(){

return(

<ChartTest />

)

} export default App;

Here’s our final result: