Issue
weird error started appearing that's causing builds to fail,
we have a post/[id].tsx file inside of our pages dir, this file uses getStaticProps
and getStaticPaths
-- props
export const getStaticProps: GetStaticProps = async ({ params }) => {
const res: Response = await fetch(`${baseUrl}/api/products/${params.id}`);
const data: Product[] = await res.json();
return {
props: {
data,
},
};
};
-- paths
export const getStaticPaths: GetStaticPaths = async () => {
const res: Response = await fetch(`${baseUrl}/api/products`);
const { data } = await res.json();
const paths = data.map((product: Product) => ({
params: { id: product.id.toString() },
}));
return { paths, fallback: "blocking" };
};
running npm run dev
locally and everything works as expected, but running npm run build
and the error
Type error: Object is possibly 'undefined'.
inside of the getStaticProps function
> 12 | const res: Response = await fetch(`${baseUrl}/api/products/${params.id}`);
^
Now the weird thing is that the currently deployed build on vercel is using the exact same code to build this page and nothing has changed from it. But now builds are suddenly failing?
Solution
The problem here is that next.js is doing a type-check here and typescript thinks your params might be undefined here. Just tell typescript it's not.
const id = params.id!
const res: Response = await fetch(`${baseUrl}/api/products/${id}`);
This should work.
Answered By - Pranta
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.