Last active
March 18, 2023 17:33
-
-
Save chengjieyun59/b7fd99da637b3babfb00169408744f3f to your computer and use it in GitHub Desktop.
Fetch from an endpoint in React functional component with hooks
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 { useState, useEffect } from 'react'; | |
import logo from './logo.svg'; | |
import './App.css'; | |
function App() { | |
const [astronauts, setAstronauts] = useState([]); | |
// setting the dependencies array in useEffect to an empty array | |
// ensures this fetch request only runs once instead of infinitely | |
useEffect(() => { | |
fetch('http://api.open-notify.org/astros.json') | |
.then(res => res.json()) | |
.then(data => setAstronauts(data.people)) | |
.catch(err => console.error(err)) | |
}, []); | |
// create a list node to add to the DOM | |
const astronautList = 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