Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NextJs how to deal with fetching and a loop

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,
  };
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading