Skip to content

Instantly share code, notes, and snippets.

@pebueno
Created February 27, 2024 14:48
Show Gist options
  • Save pebueno/78188d23d92771438487a8189ad1afc6 to your computer and use it in GitHub Desktop.
Save pebueno/78188d23d92771438487a8189ad1afc6 to your computer and use it in GitHub Desktop.
Use hooks to Fetch from URL and Resolve all Promises
import "./styles.css";
import PeopleList from "./PeopleList";
export default function App() {
const peopleIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
return <PeopleList ids={peopleIds} />;
}
import React, { useEffect, useState } from "react";
interface PeopleListParams {
// This is the list of IDs we got from our result API
ids: number[];
}
export default function PeopleList({ ids }: PeopleListParams) {
let [people, setPeople] = useState<string[]>([]);
useEffect(() => {
const fetchPeople = async (id: Number) => {
const response = await fetch(`https://swapi.dev/api/people/${id}`);
const data = await response.json();
return data.name;
};
const peopleArr = ids.map((id) => fetchPeople(id));
Promise.all(peopleArr).then((values) => {
return setPeople(values);
});
}, []);
return (
<div>
{people.map((name, i) => (
<p key={i}>{name}</p>
))}
<h1></h1>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment