Skip to content

Instantly share code, notes, and snippets.

@chengjieyun59
Last active March 18, 2023 17:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chengjieyun59/b7fd99da637b3babfb00169408744f3f to your computer and use it in GitHub Desktop.
Save chengjieyun59/b7fd99da637b3babfb00169408744f3f to your computer and use it in GitHub Desktop.
Fetch from an endpoint in React functional component with hooks
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