Home > Mobile >  Issues with React hooks/async behavior
Issues with React hooks/async behavior

Time:10-19

There is some kind of a problem with this code, so I've been "debugging" it with console.log(). The result here doesn't make any sense. What's wrong with this code? I was curious why my console.logs in "useEffect" were null, so I"ve checked it along the way and this is strange, because inside the same "if" there is a certain value, but then when it is used it suddenly is lost => null. How? Why?

enter image description here

useEffect(() => {
    getProfile()
    console.log(email)
    console.log(id)
    console.log(type)
  }, [])

  async function getCurrentUser() {
    const {

      data: { session },
      error,
    } = await supabase.auth.getSession()

    if (error) {
      throw error
    }

    if (!session?.user) {
      throw new Error('User not logged in')
    }

    return session.user
  }

  async function getProfile() {
    try {
      const user = await getCurrentUser()
      
      console.log(user.id);

      let { data, error, status } = await supabase
        .from('users')
        .select()
        .eq('uid', user.id)
        .single()
      console.log(data.type)

      if (error && status !== 406) {
        throw error
      }

      if (data) {
        console.log(data.type)
        setEmail(data.email)
        setType(data.type)
        setId(data.uid)
        console.log(type)
      }
      console.log(type)
    } catch (error: any) {
      alert(error.message)
  }

CodePudding user response:

Everything is behaving correctly. The console.log() inside the useEffect and after that async getProfile() call in the useEffect will be executed synchronously. So the first 3 logs are undefined and it is correct. The setType, setEmail and all setters returned from useState, which will update the state asynchronously (or to be more correct through a closure function), so it means, that the

setEmail(data.email)
        setType(data.type)
        setId(data.uid)
        console.log(type)

is doing its job. To log it correctly, add the type, id, and email state to the dependency array of the useEffect hook. As the data changes, it will trigger a rerender and call the useEffect again with the updated data.

  • Related