Home > Software design >  NextJs how to deal with fetching and a loop
NextJs how to deal with fetching and a loop

Time:05-18

I have a question how can I deal with fetching through loop in getStaticProps, because when I do that the array is empty. It is caused by asynchronous code. If I pass ID array and put logic into react component it works fine. Should I stick with component approach or do it in getStaticProps. If getStaticProps how can I pass data?

export const getStaticProps: GetStaticProps = async (context) => {
  
  const assetsId = await getDataFromMongo();
const assetsArray = [] as Asset[];
      console.log(assetsId);
      assetsId.forEach((asset) => {
        const getAssets = async () => {
          const response = await fetch(
            `https://rest.coinapi.io/v1/assets/${asset}`,
            {
              method: "GET",
              headers: {
                "Content-Type": "application/json",
                "X-CoinAPI-Key": "API KEY",
              },
            }
          );
          const data = await response.json();
          assetsArray.push(data);
        };
        getAssets();
      });
      console.log(assetsArray);
  return {
    props: {
      assets: assetsId,
    },
    revalidate: 1,
  };
};

CodePudding user response:

You'll want to use Promise.all here and wait for all the promises to resolve. Right now your promises resolve too late (the response has already been sent to the client and the array is empty.

export const getStaticProps: GetStaticProps = async (context) => {
  const assetsId = await getDataFromMongo();

  const promises = assetsId.map(async (id) => {
    const response = await fetch(`https://rest.coinapi.io/v1/assets/${id}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "X-CoinAPI-Key": "API KEY",
      },
    });

    return response.json();
  });

  return {
    props: {
      assets: await Promise.all(promises),
    },
    revalidate: 1,
  };
};

Also heads up, you'll probably want to increase your revalidation as 1 second will barely make a difference over just using getServerSideProps and you'll be hitting this coin api a lot!

  • Related