Skip to content

Instantly share code, notes, and snippets.

@ankitkanojia
Created September 3, 2019 03:46
Show Gist options
  • Save ankitkanojia/22243ec45071d22cf4e147345ece9016 to your computer and use it in GitHub Desktop.
Save ankitkanojia/22243ec45071d22cf4e147345ece9016 to your computer and use it in GitHub Desktop.
API call in reactjs application using axios request
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
//install axios package using 'npm i axios' command
const axios = require('axios');
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
users: [],
error: null
}
}
componentDidMount() {
this.fetchUsers();
}
fetchUsers() {
axios.get('https://jsonplaceholder.typicode.com/users')
// ...then we update the users state
.then(response =>
this.setState({
users: response.data,
isLoading: false,
})
)
// Catch any errors we hit and update the app
.catch(err => console.log(err))
}
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