'Not able to set state in react properly

I have this function which is setting the user

  const [user, setUser] = useState(null)

  const getUser = async () => {
    setIsAuth(false)
    setLoading(true)
    try {
      let temp = await axiosURL.get('/api/users/me')
      temp = temp.data
      if (temp) {
        setUser(temp)
        setIsAuth(true)
      }
    } catch (error) {
      console.log(error)
    }
    setLoading(false)
  }

After setting the user I am fecthing the data acording to the user

   const getAllScopeData = async () => {
    setLoading(true)
    await getUser()
    console.log(user)
    await getScopeOneData()
    await getScopeTwoData()
    await getScopeThreeData()
    setLoading(false)
  }

But when I am running getAllScopeData() The user details is fetching correctly and logging in the console but user from the state is not changing from null . So I am able to fetch further data .



Solution 1:[1]

the problem I see it's here

const getAllScopeData = async () => {
    setLoading(true)
    await getUser()
    console.log(user)
    await getScopeOneData()
    await getScopeTwoData()
    await getScopeThreeData()
    setLoading(false)
  }

even if you wait for the function getUser your state is not update yet

You should use useEffect like this

useEffect(async() => {
if(!user) return;
   setLoading(true)
    await getScopeOneData()
    await getScopeTwoData()
    await getScopeThreeData()
    setLoading(false)
}, [user])


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 R4ncid