I have a bunch of images - 230 images to be exact, that I want to preload using getStaticProps. However, I don't know how to preload all of them using a for loop, as the end result was undefined when I tried to call it in the console.
export async function getStaticProps() {
frameCount = 230
for (let id = 1; id < frameCount; id++) {
const res = await fetch (`https://${VERCEL_URL}/_next/image?url=%2F${id}.webp&w=1080&q=90`)
const data = await res.json
}
return {
props: {
data
}
}
}
I am not very experienced in NextJS and this is the first time I tried using a for loop in a getStaticProps to get images being preloaded by the client. Any help would be appreciated!
You can use Promise.all :
export async function getStaticProps() {
const frameCount = 230;
const data = [];
for (let id = 1; id <= frameCount; id++) {
// add new promise to array
data.push(fetch(`https://${VERCEL_URL}/_next/image?url=%2F${id}.webp&w=1080&q=90`).then((res) => res.json()));
}
return {
props: {
data: await Promise.all(data), // wait for all images to load
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.