Home  >  Q&A  >  body text

Run an async function on React return

I'm trying to display a username from a Firebase database in a React return function.

I have a function called getUserName which retrieves the username from the database and returns it.

const getUserName = async () => {
        try {
            const docRef = doc(db, "users/" + auth.currentUser?.uid);
            const userDocument = await getDoc(docRef);
            const userData = userDocument.data() as UserData;
            const userName = userData.name.split(' ')[0];
            return userName;
        } catch (error) {
            console.error(error)
            return "Failed to Retrieve UserName";
        };
    }

Then I try to display it in the return of the react component.

return (
  <div>
    Hi, {getUserName()}!
  </div>
)

But I get this error: Type 'Promise' is not assignable to type 'ReactNode'. ts(2322) const getUserName: () => Promise

Not sure what I'm doing wrong here. I'm using TypeScript, so do I need to specify the type somewhere?

P粉545682500P粉545682500432 days ago505

reply all(1)I'll reply

  • P粉009186469

    P粉0091864692023-09-08 00:16:12

    The error message is very clear. To resolve this issue, you can modify the getUserName function to use the useState hook to store the username and update it asynchronously.

    import { useState, useEffect } from 'react';
    
    const MyComponent = () => {
      const [userName, setUserName] = useState('');
    
      useEffect(() => {
        const getUserName = async () => {
          try {
            // some code here
            setUserName(userName);
          } catch (error) {
            console.error(error);
            setUserName("Failed to Retrieve UserName");
          }
        };
        getUserName();
      }, []);
    
      return (
        <div>
          Hi, {userName}!
        </div>
      );
    };

    reply
    0
  • Cancelreply