In this tutorial, we will be fetching data from an API endpoint and storing the data from it. The API used in this tutorial is a simple URL from http://jsonplaceholder.typicode.com/users/1 . We will be receiving the email address of a user from this URL.
import React, { Component } from 'react'
export default class FetchData extends Component {
constructor() {
super()
this.state = {
isLoading: true,
users : {},
}
render() {
return (
<div>
Data is rendered here...
</div>
)
}
}
First, we define a class, FetchData
, with a state containing data for when the data request is processing (isLoading) and an object for the email received after the request is received. There are many ways to go about this but we will be using one of the lifecycle methods, componentDidMount()
to achieve this. When the component is mounted a JavaScript function, fetch()
is used to send a request to the endpoint, the response received is then processed accordingly, either as an error response or a successful one. The code now looks like so:
import React, { Component } from 'react'
export default class FetchData extends Component {
constructor() {
super()
this.state = {
isLoading: true,
users : {},
}
}
componentDidMount() {
fetch('http://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => console.log(data))
}
render() {
return (
<div>
Data is rendered here...
</div>
)
}
}
When the component is rendered on the screen, a request is sent and the data received is logged to the browser console:
But what we actually want is to store the data received in our state. So we assign our state variable users to the data received, we also need to change the isLoading variable according to the stage the data request is in. So before the fetch()
request is sent, we set isLoading to true, then after the response is received it is then set to false
. The code now looks thus:
import React, { Component } from "react";
export default class FetchData extends Component {
constructor() {
super();
this.state = {
isLoading: false,
users: {},
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch("http://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json())
.then((data) => this.setState({ users: data , isLoading: false}))
.catch(err => console.log(err)
)
}
render() {
return (
<div>
<h1>{this.state.isLoading ? "Loading" :
this.state.users.email
}</h1>
</div>
);
}
}
This is a pretty fast API call so the text ‘loading’ might not be seen. In cases of large API requests, a spinner or loader to indicate that the page is functional might be really helpful, so users will not think the site has crashed. Your render method might look like this then:
render() {
return (
<div>
<h1>{this.state.isLoading ? <Loader /> :
this.state.users.email
}</h1>
</div>
);
}
}
Where the <Loader/>
is a component holding the spinner or loading styled with CSS and JavaScript. API requests will more often be made with API_HEADERS
and API_AUTHENTICATION_KEYS
. Another way to make calls is by using ‘axios
’.
Axios is a React add-on that can perform all the CRUD (Create, Read, Update, and Delete) functions. Install via the command ‘npm install axios
’.