Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
API call in reactjs application using fetch request
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
users: [],
error: null
}
}
componentDidMount() {
this.fetchUsers();
}
fetchUsers() {
fetch(`https://jsonplaceholder.typicode.com/users`)
// We get the API response and receive data in JSON format...
.then(response => response.json())
// ...then we update the users state
.then(data =>
this.setState({
users: data,
isLoading: false,
})
)
// Catch any errors we hit and update the app
.catch(error => this.setState({error, isLoading: false}));
}
render() {
const {isLoading, users, error} = this.state;
return (
<div className="App">
<header className="App-header">
<img src={logo} classNa me="App-logo" alt="logo"/>
<h4>API User Collection</h4>
{/*Display a message if we encounter an error*/}
{error ? <p>{error.message}</p> : null}
<ul>
{/*Here's our data check*/}
{!isLoading ? (
users.map(user => {
const {username, name, email} = user;
return <li> username: {username} || Name: {name} || Email Address: {email} </li>;
})
// If there is a delay in data, let's let the user know it's loading
) : (
<li>Loading...</li>
)}
</ul>
</header>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment