I need to know how to define next js Context types and and it's req types?
Here I write this getServerSideProps function-
//Server side functions
export const getServerSideProps: GetServerSideProps = async (context) => {
await getMovies(context, context.req);
return { props: {} }
}
And here I write this function-
export const getMovies = (context: **types, req: **types) => {
//here the main function
}
Here How Can I define context types and req types?
Please help me?
In VS Code, you can right click on a type and click "Go to Definition". The type of GetServerSideProps is defined inside next.js as:
export type GetServerSideProps<
P extends { [key: string]: any } = { [key: string]: any },
Q extends ParsedUrlQuery = ParsedUrlQuery,
D extends PreviewData = PreviewData
> = (
context: GetServerSidePropsContext<Q, D>
) => Promise<GetServerSidePropsResult<P>>
So it looks like the context parameter is a GetServerSidePropsContext, with some generic parameters.
Which means your function becomes:
import type {
GetServerSideProps,
GetServerSidePropsContext,
PreviewData,
} from "next";
import { ParsedUrlQuery } from "querystring";
// ...
export function getMovies<Q extends ParsedUrlQuery, D extends PreviewData>(
context: GetServerSidePropsContext<Q, D>,
req: GetServerSidePropsContext<Q, D>["req"]
) {
// ...
}
I would just drop the req parameter though, it's already in context. Extract it inside getMovies if you must.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With