I have this component
import React from 'react'
export const MainPage = async () => {
let resp = await fetch(`http://localhost:8000/users/63fc9a335a6f38aa2dd47d15`, {
method: 'get',
headers: { 'x-access-token': 123 }
});
let user = await resp.json();
return (
<div>MainPage
</div>
)
}
export default MainPage;
And I call her on the app:
function App() {
return (
<div className="App">
<MainPage/>
</div>
);
}
Then I get 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.
I understand it’s because the function returns a promise but I don’t know how to call it another way.
Would appreciate help.
2
Answers
React components can’t be async. You should move your code to fetch to a useEffect with an empty dependency array.
async
cannot be used with function components.use the
useState
hook to set the data once it is fetched, and display it in the component