Getting null values from state before fetching actual data from API call in React

Viewed 546

I understand that there is a initial state of the data i.e 'null' before fetching the data from API call. But when API is called the data should update , instead log shows me 2 null values before logging actual data.

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [data, setData] = useState(null);

    const { user } = isAuthenticated();

    useEffect(() => {
        getUser(user.userId)
            .then()
            .then(
                (result) => {
                    setIsLoaded(true);
                    setData(result);
                },
                (error) => {
                    setIsLoaded(true);
                    setError(error);
                }
            )
    }, [])

    console.log(data)

enter image description here

Why am I getting these null values before actual data? How to avoid these null values? Those initial null values are causing errors if I try to show that value on page.

1 Answers

Due to StrictMode (calling render function twice) you get two logs of null in the console on the first render.

Also, you have two state changes that aren't batched (setIsLoaded, setData), React doesn't batch state changes in promises.

Therefore you have log (null) on the first render, another one (null) on setIsLoaded, and finally the data from setData.

And because you use useEffect, the callback will be called after the first render.

Related