1
I’m using the function getStaticProps
from Next.js and Axios to pick up news from Hacker News. My goal is to access the API that returns the main stories of the day (which returns a unique id of those stories) and then take the first five ids of that return and make a new request through Axios to access their content. At the end step the content as props for the component that will render the news.
The problem is that to get the first five I need to use map to access the results asynchronously. The console.log
in the code returns empty precisely because of the time of the code. I already searched some results using Promise.all
but none that applies to that case.
So the question is: How do I perform the process described above using map
asynchronous?
export async function getStaticProps() {
const res = await axios.get('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
const allData = await res.data
let data = []
allData.slice(0, 5).map(async function(story) {
try {
let itemRes = await axios.get(`https://hacker-news.firebaseio.com/v0/item/${story}.json?print=pretty`)
const itemData = await itemRes.data
data.push(itemData)
} catch (e) {
console.log(e)
}
})
console.log(data)
return {
props: { data }
}
}
Thanks for the editing and comments. However, when you used Promise.all() I think you forgot to add files as a parameter. I added it to my code and it worked. If you can check this please.
– Mateus Queirós
That’s right, sorry for the error! It’s already edited. Thanks. :) cc @Mateusqueiros
– Luiz Felipe