简体   繁体   中英

Objects are not valid as a React child (found: [object Promise]) next js 13

Why do I get this error when I make my page an async function? everything works fine when it isn't an async function. The only difference is that it returns a pending object which isn't what I want.

this is how I fetch the data:

const getData = async (id) => {
const res = await fetch({
    url: "http://localhost:3000/api/user/getOne",
    method: "POST",
    credentials: true,
    body: {
        userId: "637846eb8f36e20663a9c948",
    },
});
return res;

};

and then this is the page function

export default async function Page() {

const profileData = await getData();

useEffect(() => {
    console.log(profileData);
}, []);
return(<div><p>Hello</p></div>)
}

I think the problem has to do with the async function and the await. How do I fix this?

Move the async in useEffect

export default function Page() {    
    
    useEffect(() => {    
      
     const getAll= async () => {
        const profileData = await getData();
        console.log(profileData);

     };

     getAll(); // run it, run it
    }, []);
    
  return(<div><p>Hello</p></div>)
}

Could try the idea as the below code.

import { useState } from "react";

export default async function Page() {
    const [profileData, setProfileData] = useState([]);
    async function initDate() {
        const response = await getData();
        setProfileData(response);
    }
    useEffect(() => {
        initDate();
        console.log(profileData);
    }, []);
    return (<div><p>Hello</p></div>)
}

It's not good to call a function directly inside of the component body in client components because every time with re-rendering of the component, your function gets executed.

It's better to write them in useEffect with dependencies.

If you want to run the function only once, you should use an empty array as the dependency:

useEffect(() => {
  // your code
}, []);

And if you want to run them whenever one or more states change, you should do this:

useEffect(() => {
  // your code
}, [/* list of the dependencies */]);

So in your case, it would be like this:

useEffect(() => {
  const getProfileData = async () =>  {
    await getData();
  }

  getProfileData();
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM