Module 5: Data Fetching

Lesson 1: getStaticProps

getStaticProps is a method used to fetch data at build time. This is ideal for pages where the content doesn’t change frequently, ensuring high performance and scalability.

How It Works:

  • Use getStaticProps in any page component.
  • Fetch data during the build process.
  • Example:

export async function getStaticProps() {
const data = await fetch(‘https://api.example.com/data’).then(res => res.json()); return {
props: { data },
};
}

export default function Page({ data }) { return <div>{JSON.stringify(data)}</div>;
}

Advantages:

  •  Improved performance with pre-rendered pages.
  • Content is served as static HTML.

 Limitations:

  •  Pages require rebuilding to update data.

Lesson 2: getServerSideProps

getServerSideProps is a method used to fetch data on each request. It’s suitable for dynamic content that changes frequently or user-specific data.

How It Works:

  • Use getServerSideProps in your page component.
  • Fetch data on every request to the server.
  • Example:

export async function getServerSideProps(context) {
const data = await fetch(‘https://api.example.com/data’).then(res => res.json()); return {
props: { data },
};
}

export default function Page({ data }) { return <div>{JSON.stringify(data)}</div>;
}

Advantages:

  •  Always serves the latest data.
  •  Ideal for personalized or time-sensitive content.

Limitations:

  •  Slower performance compared to static methods.

Lesson 3: getStaticPaths

getStaticPaths works alongside getStaticProps to generate dynamic routes for static pages. It’s used when pre-rendering pages with dynamic parameters.

How It Works:

  • Define paths at build time.
  • Use getStaticPaths to return a list of route parameters.
  • Example:

export async function getStaticPaths() {
const data = await fetch(‘https://api.example.com/posts’).then(res => res.json()); const paths = data.map(post => ({ params: { id: post.id.toString() } }));

return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
const post = await fetch(`https://api.example.com/posts/${params.id}`).then(res => res.json()); return { props: { post } };
}

export default function Post({ post }) { return <div>{post.title}</div>;
}

Options for ******** fallback :

  •   false : Only generate specified paths. Requests for undefined paths return a 404.
  •   true : Generate new paths on the fly and cache them.
  •   blocking : New paths are generated during request but delay the response until complete.

Advantages:

  •  Supports dynamic routing with pre-rendered pages.
  • Flexible with fallback options.

Limitations:

Requires careful handling of undefined routes if fallback is used.

Additional Resources

Data Fetching Docs


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *