Skip to content

Instantly share code, notes, and snippets.

@ankitkanojia
Created September 3, 2019 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankitkanojia/96b5c0481226ec0bfa1f2f682d0f28e8 to your computer and use it in GitHub Desktop.
Save ankitkanojia/96b5c0481226ec0bfa1f2f682d0f28e8 to your computer and use it in GitHub Desktop.
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