Alhasawi
Alhasawi

Reputation: 1

How can I handle errors and ensure type safety in getStaticProps in Next.js with TypeScript?

I'm working on a Next.js project using TypeScript, and I'm trying to properly handle errors and ensure type safety in the getStaticProps function. I have a page that fetches data at build time, but I'm not sure how to handle potential errors during data fetching and how to type the props correctly. Here is an example of my code:

// types.ts
export interface Post {
  id: string;
  title: string;
  content: string;
}

// posts.tsx
import { GetStaticProps, InferGetStaticPropsType } from 'next';
import { Post } from '../types';

interface Props {
  posts: Post[];
  error?: string;
}

const PostsPage = ({ posts, error }: InferGetStaticPropsType<typeof getStaticProps>) => {
  if (error) {
    return <div>Error: {error}</div>;
  }

  return (
    <div>
      {posts.map((post) => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.content}</p>
        </div>
      ))}
    </div>
  );
};

export const getStaticProps: GetStaticProps<Props> = async () => {
  try {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!res.ok) {
      throw new Error('Failed to fetch');
    }

    const posts: Post[] = await res.json();

    // Transform the data if necessary to match the Post interface
    const transformedPosts: Post[] = posts.map((post: any) => ({
      id: post.id.toString(),
      title: post.title,
      content: post.body,
    }));

    return {
      props: {
        posts: transformedPosts,
      },
    };
  } catch (error) {
    return {
      props: {
        posts: [],
        error: (error as Error).message,
      },
    };
  }
};

export default PostsPage;

Desired behavior:

Ensure the getStaticProps function is correctly typed to provide type safety.
Properly handle errors during the data fetching process and pass them to the component.

What I've tried:

Using GetStaticProps<Props> for typing the getStaticProps function.
Attempting to catch errors and pass them as props, but I'm not sure if this is the best practice.

Specific problem or error:

I'm uncertain about the best way to handle errors in getStaticProps and ensure that the props are correctly typed.

Environment details:

Next.js version: 14.2.3
TypeScript version: 5.4.5
Running on: macOS

Any insights or best practices on how to handle errors and ensure type safety in getStaticProps in Next.js with TypeScript would be greatly appreciated. Thank you!

Upvotes: 0

Views: 27

Answers (0)

Related Questions