Just a basic question regarding `.auth.onAuthState...
# help
k
Just a basic question regarding `.auth.onAuthStateChange()`: I'm having what seems to be a classic react timing problem with the session & the logged in user. My question is simple, when
.auth.session() === Session
(not
null
), does that trigger
.auth.onAuthStateChange()
? Or is that only for login/signup/logout/password recovery, etc etc...
s
As far as I'm aware, it triggers for any changes to the auth (session, users, etc) such as when there's a sign in, sign out, token refresh, etc. For example, I use the
react-supabase
library (https://react-supabase.vercel.app/documentation/auth/use-auth-state-change), and noticed that it triggered on its own periodically due to the old user access token expiring and a new one being generated. You can do something like this (react native example which navigates the user based on their access_token):
Copy code
js
useAuthStateChange(async (event, session) => {
  if (!session?.access_token) {
    navigation.reset({
      routes: [{ name: "my_authed_route" }],
    });
    return;
  }
  if (session?.access_token) {
    // User has an access token
    // Redirect to main screen, etc
    return;
  }
});
You could also do something like this if you prefer:
Copy code
js
useAuthStateChange((event, session) => {
  if (event === "SIGNED_OUT") {
    // Redirect user to login screen
    return;
  }
});
Not sure if that answers your question, but leave a reply if you need any clarification on specifics
k
Thank you for your response, I'll have to compare notes later. I'll have to check out that library, as well.