Home > Mobile >  Displayed data does not update
Displayed data does not update

Time:06-11

I am using a function to fetch some data and display the data returned. The problem: The data does not display.

function Profile() {

    const profileUser = getData(userId)
    
    return (
        <div>
            <p>{profileUser?.name}</p>          
        </div>
    )
}

The getData is an asynchronous function returning fetching data from firebase while using await and returning an object.

CodePudding user response:

You'll probably want to store profileUser in state and then use useEffect to fetch that data when the component mounts

function Profile() {
    const [profileUser, setProfileUser] = useState();

    useEffect(async () => {
        const user = await getData(userId);
        setProfileUser(user);
    }, []);
    
    return (
        <div>
            <p>{profileUser?.name}</p>          
        </div>
    )
}

CodePudding user response:

larz answer is good, but you may get a warning/error about useEffect being async. You aren't supposed to have an asyncronous useEffect method. There is a workaround though.

You need to define an async function inside of the useEffect hook that calls your async function. Then use that data to set the state. You need the state since that is what makes it reactive.

function Profile() {
    const [profileUser, setProfileUser] = useState({});

    useEffect(() => {
      const fetchUserProfile = async () => {
        const user = await getData()
        setProfileUser(user);
      } 

      fetchUserProfile()
    }, []);
    
    return (
        <div>
            <p>{profileUser?.name}</p>          
        </div>
    )
}

Importantly, dont await your fetchUserProfile call, since again, the useEffect method is not async.

  • Related