Created
February 27, 2024 14:48
-
-
Save pebueno/78188d23d92771438487a8189ad1afc6 to your computer and use it in GitHub Desktop.
Use hooks to Fetch from URL and Resolve all Promises
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 "./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} />; | |
} |
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, { 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