Created
March 5, 2021 05:50
-
-
Save chengjieyun59/6a9531704620631bdb0d43caaaa4a630 to your computer and use it in GitHub Desktop.
Fetch from an endpoint in React class component with state
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); | |
// 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