Run an async function on React return
P粉545682500
P粉545682500 2023-09-07 17:31:08
0
1
457

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粉545682500
P粉545682500

reply all(1)
P粉009186469

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>
  );
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!