I am trying to use async on page.tsx in nextjs 13 "app" approach and keep gettin this error:
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
here’s the code example:
const AsynCfun = async () => {
// reason i use async is because i have await on the http request
const posts = await fetchPosts();
return <div>async print posts...</div>
}
export default function Sidebar() {
return <div>sidebar <AsynCfun/></div> // error...
}
2
Answers
Ok so I end up finding the answer, my problem was
Component in client:
component in server side (which is async with server side fetch):
code taken from here: https://lior-amsalem.hashnode.dev/nextjs-error-objects-are-not-valid-as-a-react-child-found-object-promise-if-you-meant-to-render-a-collection-of-children-use-an-array-instead
don’t think you can have async components in React since rendering is synchronous. Here you can use state and useEffect.
Then can render as normal in sidebar. One thing is useEffect callback cannot be async directly so you have to create async function and perform any stateful operations within as shown above.
Hope it helps,
Best