skip to Main Content

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


  1. React components can’t be async. You should move your code to fetch to a useEffect with an empty dependency array.

    export const MainPage = () => {
      const [resp, setResp] = React.useState(undefined);
    
      React.useEffect(async () => {
        const resp = await fetch(`http://localhost:8000/users/63fc9a335a6f38aa2dd47d15`, {
          method: 'get',
          headers: { 'x-access-token': 123 }
        });
        setResp(await res.json());
      }, []);
    
      if (!resp) {
        // Optional: make it show something else while the request is still loading.
        return <div>Loading</div>;
      }
      
      return (
        <div>MainPage</div>
      )
    }
    
    Login or Signup to reply.
  2. 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

    import React, { useState, useEffect } from 'react';
    
    const fetchData = async () => {
      const resp = await fetch(`http://localhost:8000/users/63fc9a335a6f38aa2dd47d15`, {
        method: 'get',
        headers: { 'x-access-token': 123 }
      });
      const data = await resp.json();
      return data;
    };
    
    const MainPage = () => {
      const [userData, setUserData] = useState(null);
    
      useEffect(() => {
        fetchData().then(data => setUserData(data));
      }, []);
    
      return (
        <div>
          {userData ? (
            <div>
              <h1>MainPage</h1>
              <img src={userData.picture} alt="User" />
              <p>Contact Information: {userData.contactInfo}</p>
              <button>{userData.buttonText}</button>
            </div>
          ) : (
            <p>Loading data...</p>
          )}
        </div>
      );
    };
    
    export default MainPage;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search