skip to Main Content

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


  1. Chosen as BEST ANSWER

    Ok so I end up finding the answer, my problem was

    Component in client:

    "use client" // its ok to use use client. this component is for FE!
    export default function SomeForntEndComponent() {
        useEffect(() => {
            // usage of useEffect! its a client behaviour!
        }, []);
    
        return (<div className="main">
            <h1>Sub component = its fe behaviour</h1>
        </div>
      )
    }
    

    component in server side (which is async with server side fetch):

    // profile/page.tsx entity file
    // it's ok to do a async fetch, this is possible both on front end and backend:
    async function fetchData(promptslug:string) { 
        let res = await fetch(`http://localhost:3000/api/data`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                'Accept': 'application/json'
            },
        });
    
        if(!res.ok) {
            throw new Error('Fail fetch');
        }
    
        return res.json();
    }
    
    
    // usage of async on a page component
    export default async function Page() {
        const data = await fetchData();
    
        return (<div className="main">
            <h1>Hello World</h1>
        </div>
      )
    }
    
    

    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


  2. don’t think you can have async components in React since rendering is synchronous. Here you can use state and useEffect.

    const AsynCfun = () => {
      const [posts, setPosts] = useState();
    
      useEffect(() => {
        const fetchAndSetData = async () => {
          const data = await fetchPosts();
          // do whatever needs to be done on data
          setData(data);
        };
        fetchAndSetData();
      });
    
      return <div>async print posts...</div>;
    };
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search