Skip to content

Instantly share code, notes, and snippets.

@chengjieyun59
Created March 5, 2021 05:50
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 chengjieyun59/6a9531704620631bdb0d43caaaa4a630 to your computer and use it in GitHub Desktop.
Save chengjieyun59/6a9531704620631bdb0d43caaaa4a630 to your computer and use it in GitHub Desktop.
Fetch from an endpoint in React class component with state
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
// initialize the astronauts with an empty array
// to avoid running into null pointer exceptions
// after the first render, but before the componentDidMount() gets called
this.state = {
astronauts: [],
api: 'http://api.open-notify.org/astros.json',
};
}
// make sure to fetch from this React life cycle
componentDidMount() {
// use JavaScript's fetch API
fetch(this.state.api)
.then(res => res.json())
.then(data => {
// update the component's local state to the json object's people array
this.setState({
astronauts: data.people
});
});
}
render() {
// create a list node to add to the DOM
const astronautList = this.state.astronauts.map((astronaut, index) => (
<li key={`astro-${index}`}>
<p>{astronaut.name} is flying in the {astronaut.craft} spacecraft</p>
</li>
));
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<ul>
{astronautList}
</ul>
</header>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment