0

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)
  }
IVOBOT
  • 61
  • 8

1 Answers1

1

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.

Burak Ayyildiz
  • 325
  • 1
  • 6
  • Though can it not display null for the first time so that it loads before render/the rest of typescript? How to rewrite it? – IVOBOT Oct 18 '22 at 14:10
  • can you try like this: useEffect(() => { getProfile() console.log(email) console.log(id) console.log(type) }, [email, id, type]) – Burak Ayyildiz Oct 19 '22 at 15:02