2

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.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Sweta Dash
  • 45
  • 5

1 Answers1

1

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.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • Not using StrictMode! – Sweta Dash Mar 11 '21 at 05:14
  • 2
    Yes, you have another state change `setIsLoaded` on complete, state change in promises **not** batched. – Dennis Vash Mar 11 '21 at 05:17
  • Yes you were right , just by changing the order of setData() and setIsLoaded() removed one null value. Still one null exists though. – Sweta Dash Mar 11 '21 at 05:40
  • Ofc it exists, you have an initial value null, and as mentioned in the answer ***useEffect callback runs after the first render**** – Dennis Vash Mar 11 '21 at 05:41
  • I tried not using useEffect() and just called the function, it logged data indefinitely, still got the first one null, which is obvious because that' the initial value. Any idea on how should I tweak the code to handle that initial null value? – Sweta Dash Mar 11 '21 at 05:54
  • 1
    You shouldnt tweak nothing, thats how it works, read about conditional rendering, and read about ajax calls in React docs – Dennis Vash Mar 11 '21 at 06:00