How to fetch APIs in react and effectively use data responses to create graphs using recharts
React is a nice JavaScript framework that allows developers to create interfaces by implementing simple building blocks called components. What sets react apart from more traditional web development frameworks is that it automatically uses its internal logic to render the section of the user interface that needs to be updated based on props and state changes (more on that later).
In this tutorial, we are going to call a stock market prices API to design a graph using the library “recharts.js”.
To unlock the full potential of the react framework, simply type the below commands on the command line .
create-react-app apis
This will help create a new project called apis (or whatever else you want to call it 😀). We will also use the command line to install recharts.
npm install recharts
Once you are done with those steps, go to your app.js and add the following code 👇. This code will render the graph component that you will implement in a file called graph.js
import React from 'react';
import Graph from './graph';function App() {return (<Graph/>);}export default App;
In graph.js, we need to first import the important dependencies for this project.
import React from "react"import { useState, useEffect } from "react";import {Line, LineChart, Tooltip} from 'recharts'
- useState is a react hook which allows functional components to manage react states.
UseEffect is a functional implementation of componentDidMount,componentDidUpdate, and componentWillUnmount
Before we implement the get requests , we need to head over to this website to get our API key.
Our graph.js file will look like this:
//this line imports react functionalityimport React from 'react';import { useEffect, useState } from "react";import { LineChart, Line, Tooltip } from 'recharts';export default function App() {const [error, setError] = useState(null);const [isLoaded, setIsLoaded] = useState(false);const [items, setItems] = useState([]);const data = [];// Note: the empty deps array [] means// this useEffect will run once// similar to componentDidMount()useEffect(() => {fetch("https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=IBM&apikey=" + process.env.REACT_API).then(res => res.json()).then((result) => {for (var instance in result["Weekly Time Series"] ) {var mydata = (result["Weekly Time Series"][instance])mydata.date= instancedata.push(mydata)}setItems(data.reverse())},// Note: it's important to handle errors here// instead of a catch() block so that we don't swallow// exceptions from actual bugs in components.(error) => {setIsLoaded(true);setError(error);})}, [])return (<div><LineChart width={500} height={250} margin={{ top: 150, right: 30, left: 20, bottom: 5 }} data={items}><Line dot={false} type="monotone" dataKey="1. open" stroke="rgb(0,200,5)" yAxisId="100" /></LineChart></div>)}
This React code generates the graph below 👇:
let’s back up for a second and try to understand the react code by breaking it down . For a better grasp of the explanation, you can print the data response in the console with console.log(result)
useEffect(() => {fetch("https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=IBM&apikey=" + process.env.REACT_API).then(res => res.json()).then((result) => {for (var instance in result["Weekly Time Series"] ) {var mydata = (result["Weekly Time Series"][instance])mydata.date= instancedata.push(mydata)}setItems(data.reverse())},// Note: it's important to handle errors here// instead of a catch() block so that we don't swallow// exceptions from actual bugs in components.(error) => {setIsLoaded(true);setError(error);})}, [])
Because of useEffect , the above code is only going to run when the variables specified in the corresponding array [] are modified. In this case, the array is empty. This means that the code will only run once (At loading time).
- The fetch method allows us to make an HTTP request to the stock API
- We specify
function= TIME_SERIES_WEEKLY
which gives us access to one thousand weeks of stock data. - We also specify
Symbol= MSFT
to request Microsoft stock data. process.env.REACT_APP
retrieves the API key from the .env file- It is important to notice that the data is reversed with
data.reverse()
before being stored in the state-array. This is done to prevent the graph from displaying from right to left (We want most recent values to display on the right)
Now, let’s analyze the recharts part of the code.
- Width and height help to specify the dimensions of the graph.
- The dot prop is set to false to erase the dots.
- The state-array items is passed to the data prop to generate the intended graph. However, there are several values in the state-array; therefore to specify that we are interested in the opening price of the stock for that day. We use the prop dataKey. In our case, we specify
dataKey=”1. open”
.
<LineChart width={500} height={250} margin={{ top: 150, right: 30, left: 20, bottom: 5 }} data={items}><Line dot={false} type="monotone" dataKey="1. open" stroke="rgb(0,200,5)" yAxisId="100" /></LineChart>
We can customize the tool tip to show the specific stock values for a particular stock on a specific day when we hover over the graph. To do that, we can use the <tooltip /> component along with a customTooltip function.
We will add the following line 👇 to our linechart component:
<Tooltip content={<CustomTooltip data={items} />} />
This line of code passes the items array to the data prop available in the Tooltip component.
We define our customTooltip function as follows:
function CustomTooltip(props) {var price = ""var date = ""console.log(props)if (props.data[props.label]) {price = props.data[props.label]["1. open"]date = props.data[props.label]["date"]}return (<div><div >{date} </div><div style={{ color: "rgb(0,200,5)"}}> $ {price}</div></div>)}
This code uses the label prop and the date prop to generate this customized tool tip.
😊 Hope this tutorial helped with Recharts and fetching data from APIS in react. Check out the code on GitHub. Feel free to interact with me in the comment section.
Find me on LinkedIn 🔥