Created
September 3, 2019 03:47
-
-
Save ankitkanojia/96b5c0481226ec0bfa1f2f682d0f28e8 to your computer and use it in GitHub Desktop.
API call in reactjs application using fetch request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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