Why onAuthStateChange load multiple times still ev...
# help-and-questions
j
Hello there! Basically, I want to save my login user data to my database, but here's the issue: when I put supabase.auth.onAuthStateChange on my next page/_app.js, it makes it loop and ratelimit my database API.
Copy code
js
    supabase.auth.onAuthStateChange(async (event) => {
      if (!event) return;
      if (event === 'SIGNED_IN') {
        console.log('User signed in'); //this spam in console multiple times without load page
      } else return
    });
c
Idk if this helps but Ive solved it like this:
Copy code
function handleAuthStateChange() {
    fetchCurrentUser()
    backbase.auth.offAuthStateChange(handleAuthStateChange);
}
  
backbase.auth.onAuthStateChange(handleAuthStateChange);




const fetchCurrentUser = async () => {
        
        const { data: { user }, error } = await supabase.auth.getUser()

        if (error) {
            setFetchUserError('could not fetch user')
            setCurrentUser(null)
            console.log(error)
        }

        if (user) {
            setCurrentUser(user || [])
            setFetchUserError(null)
        }

        console.log("SIGNED IN")
    }
It's far from perfect and really weird because it constantly throws an error that offauthstatechange isnt a function, yet it still functions like offauthstatechange is a function and the line does its job. (Feel free to ignore this because this might hinder you more than help.)
j
hmm but friend there is no function as supabase.auth.offAuthStateChange
c
Thats what I mean, its really weird. Indeed there is none and it throws an error, yet the line does what it needs to do and don't when I remove it.