Fetching Covid-19 Data using React.js, Material UI, and Material-Table Part 2

Big Zude
6 min readMar 29, 2020
Photo by Fusion Medical Animation on Unsplash

In part 1 we focused on setting up our development environment where we installed create-react-app, Material UI, and Material-table. I shared the resources which we are going to use in this section. If you did not have a chance to read Part 1 click here.

In this part, it’s all technical! We are going to write code for the Cards(functional component) and WordTable(class component) components. In addition to this, we are going to implement the Effect Hook(useState and useEffect) and the Fetch API.

Let’s code! First, we are going to import react to our card functional component which we created in part 1.

import React from 'react'

Now let’s create our function

export default function Cards() {  
const greeting = 'Hey Functional Component!';
return(
<p>{greeting}</p>;
);
}

Our Card component should look like the code snippet below

We are going to create cards using Material UI. Material UI provides its users with a template example just like bootstrap etc which makes work easier and faster. For our cards, we need to import Card, CardContent, and CardMedia.

import Card from '@material-ui/core/Card';import CardContent from '@material-ui/core/CardContent';import CardMedia from '@material-ui/core/CardMedia';

Note! Styles are provided in Material UI and you are free to change them. below is the styling that we are going to use. Always place the styling above our main function and below the imports in a functional component.

Replace the paragraph tag with the code below. You don’t have to worry about styling! Material UI does that for you. Styling is done in the same file you working in and not from external sources(Inline and internal CSS is applied in Material UI).

Nice, copy and paste the card twice times. the first card should have a heading of TOTAL CASES, the second card should be TOTAL DEATHS, and the third card should be TOTAL RECOVERED like in the image below with placeholder figure.

The complete Cards Component in the code snippet below.

The time ya’ll have been waiting for! let’s fetch our data from the API but before we continue, we are going to import useState and useEffect from react. check example below

import React, { useState, useEffect } from 'react';

Sweet! let’s create our state which should be initialized to an empty array. The state is where our data from the API will be stored and should be in the main function. useState helps us to bring states to functional components.

const [stats, handleStats] = useState([]);

Let’s check what our API is returning before we go forward, So how do we do that? Well just copy the URL (‘https://corona.lmao.ninja/all’) and paste in the browser then hit enter if you don’t have postman.

Returned data

Fab! We are going to create a function that fetches the data from the API. The function will be named FetchData and the concept of async-await will be implemented in our function to handle asynchronous requests. Learn more about async await here.

const FetchData = async () => {
const data = await fetch('https://corona.lmao.ninja/all');
const stats = await data.json();
handleStats(stats)
}

The useEffect is always called when the component updated… It executes the function inside it and has an array which is an optional second param. In our case, FetchData( ) will be called inside the useEffect. check the code snippet below

useEffect(() => {FetchData()// the function fetching the data}, [])

How do we show the fetched data in the cards we created earlier? Well, that’s pretty simple and straight forward. Remember our fetched data is stored in an array in the state we created earlier. We are only fetching cases, deaths, and recovered, for example {(name of the state) dot (fetched data)}. Replace the static numbers we added to our cards with the code below.

{stats.cases} //will fetch cases (first card)
{stats.deaths} //will fetch deaths (second card)
{stats.recovered} //will fetch recovered (Third card)

Final Card Component

Our cards after data fetching

Let’s work on our final piece of the puzzle! The table, which will be implemented with Material-Table. This will be a class component, unlike the Cards component which was a functional component, the reason is that we need to have experience using before a class and functional component.

Open the WorldTable.js component, import React, and MaterialTable.

import React from 'react';import MaterialTable from 'material-table';

Awesome! Now let’s create our class-based component.

class WorldTable extends Component {constructor(props) {super(props);render() {return (<div></div>)}}
export default WorldTable;

Let’s create the state! initialize it with an empty array and set loading to false.

state = {loading:false,stats: [],}

Material-Table provides different tables and you are free to use any. With that said here is our table which we placing between the <div></div>. Then replace the <div></div> with <React.Fragment></React.Fragment>

<MaterialTable style={{marginLeft:'10px', marginRight:'10px'}}title="Worldwide Covid-19 Stats"columns={[{ title: 'Country', field: 'country' },{ title: 'Total Cases', field: 'cases' },{ title: 'Current Cases', field: 'todayCases' },{ title: 'Total Deaths', field: 'deaths', type: 'text' },{ title: 'Current Deaths', field: 'todayDeaths' },{ title: 'Recovered Patients', field: 'recovered' },{ title: 'Active Patients', field: 'active' },{ title: 'Critical Patients', field: 'critical' },{ title: 'Cases/million', field: 'casesPerOneMillion' },]}

The best part of using Material-Table is that you can add actions and options such as refresh in the table etc. You can also add styling within the options object.

actions={[{icon: 'refresh',tooltip: 'Refresh',isFreeAction: true,onClick: () => this.tableRef.current && this.tableRef.current.onQueryChange(),},]}options={{headerStyle: {backgroundColor: '#3f51b5',color: '#FFFF'}}}

Scroll up and place the code in the snippet below in the constructor. “Refs provide a way to access DOM nodes or React elements created in the render method.

this.tableRef = React.createRef();

This is the current state table of our table. Cool right?

Table

Cool! Its time to create a function that fetches our data. We are going to use componentDidMount( ) and the fetch API. I believe you have noticed the difference between our Cards and WorldTable component when fetching data. First things first, set loading to true since we are fetching data. After fetching the data set stats state to the data we are fetching.

componentDidMount() {this.setState({ loading: true })fetch('https://corona.lmao.ninja/countries') //data source.then(response => response.json()).then(res => {this.setState({ stats: res, loading: false }, () => console.log(res))}).catch(error => {console.log(error)})}

Take a break!

We are almost done. To display the data in our table, call our state in the table below the columns. How do we achieve this? Well, check the code snippet below.

data={this.state.stats}

This is how our component should look now, Well done!

The final step is to simply import the Cards and WorldTable components in App.js which is rendering all our components.

function App() {return (<div className="App"><Navbar/><Cards/><WorldTable/></div>);}export default App;

This is our final product after writing all these lines of code and fixing bugs…..Congrats!

Thanks for taking the time to read my article, I hope you have learnt something new. If you had difficulties understanding some concepts that’s normal don’t be discouraged, just continue learning.

--

--

Big Zude

React Frontend Engineer | Mobile Developer | UI Designer