Home > Back-end >  Returning data from getStaticProps
Returning data from getStaticProps

Time:10-13

I'm trying to create a function that fetches data from The Guardian API but seem to be getting an error. The response returns this information: enter image description here

And here is the code for the asynchronous function:

export async function getStaticProps() {
  try {
    const res = await fetch(
      "https://content.guardianapis.com/search?api-key=xxxxxxxx&show-fields=thumbnail"
    );
    const { results } = await res.json();
    const newsList = results.map((news) => {
      return { ...news };
    });
    return {
      props: { newsList },
    };
  } catch (err) {
    console.error(err);
  }
}

CodePudding user response:

You almost got it. Only 1 thing you are missing is to return props even in the catch block

export async function getStaticProps() {
  try {
    const res = await fetch(
      "https://content.guardianapis.com/search?api-key=xxxxxxxx&show-fields=thumbnail"
    );
    const { results } = await res.json();
    const newsList = results.map((news) => {
      return { ...news };
    });
    return {
      props: { newsList },
    };
  } catch (err) {
    console.error(err);
    return {
      notFound: true /// for rendering 404 page
    };
  }
}
  • Related