I am creating simple clone for Hacker news, I want to use useEffect
and inside it I return ids then use these ids to get first 50 posts.
The problem is with second function inside fetchHackerNewsPosts
that it doesn't wait it to add data inside the postsArray
and it prints it empty.
import React from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
let postsArray = [];
async function fetchHackerNewsPosts() {
try {
// it waits this function
let postsIDsArray = await fetch(
"https://hacker-news.firebaseio.com/v0/topstories.json"
)
.then((res) => res.json())
.then((result) => {
return result;
});
// it doesn't wait this function
await postsIDsArray.slice(0, 50).map((postId) => {
fetch(`https://hacker-news.firebaseio.com/v0/item/${postId}.json`)
.then((res) => res.json())
.then((result) => {
postsArray.push(result);
});
});
} catch (error) {
console.log(error);
}
}
fetchHackerNewsPosts();
console.log(postsArray);
}, []);
return (
<div className="p-10">
<header className="">
<h1> Hacker news API </h1>
</header>
<div className="bg-blue-600">list</div>
</div>
);
}
export default App;