So I just started using the NextPage
type provided by Next.js while writing components because I was explained it’s a very good practice, but it works only on client side components. In other words this server component throws an error because it’s an async await
.
The component:
const Page: NextPage = async () => {
const { products }: { products: CoffeeInterface[] } = await getData(
"/products"
)
return (
<main className="flex min-h-screen flex-col bg-gradient-to-t from-slate-300 via-slate-200 to-gray-200">
<SearchCoffee />
<div className="flex gap-10 w-full">
<FiltersDropdown />
<CoffeesList coffees={products} />
</div>
</main>
)
}
export default Page
The error:
Type '() => Promise<JSX.Element>' is not assignable to type 'NextPage'.
Type '() => Promise<JSX.Element>' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
Type '() => Promise<JSX.Element>' is not assignable to type 'FunctionComponent<{}>'.
Type 'Promise<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, keyts(2322)
What type should a Server Side Component return, if any? Or should I just write the server components as basic functions without mentioning the type?
I’m using Next.js 13.4
.
3
Answers
NextPage
is used for page components in thepages
directory of Next.js (the initial way of setting up routes). In theapp
directory since Next.js 13, the default export of apage.tsx
could have this type:params
andsearchParams
are the only type you can provide, and those will be passed to your component by Next.js. If you don’t need them, you can avoid defining them. The return type is most of the time inferred by TypeScript, so you don’t have to type it.For non-page components, you should type them as any function, again, most of the time, you only need to type its
props
if it has, the return type being inferred.this is
NextPage
type:I think it is meant to be used for pages directory as the note says.
InitialProps
might refer to the props that passed from the serverside functions (getServerSideProps, getStaticProps) which do not exist inapp
directory. In server components, its type will inferred automatically like thisif you have this page:
its type will be
This error is throw by the typescript because you are usin async await in react component so you have to define What the type of result is return from the react function
Try This: