Skip to content

Commit

Permalink
feat: receive a new user state every time an auth event happens
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoluoboding committed Aug 16, 2023
1 parent 124b221 commit a297c62
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions packages/auth/UserContextProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default defineComponent({
)

return () => {
console.log('authListener')
// console.log('authListener')
authListener?.subscription.unsubscribe()
}
})
Expand All @@ -45,15 +45,31 @@ export default defineComponent({
export const useSupabaseUser = (supabaseClient: SupabaseClient) => {
const supabaseUser = ref<User | null>(null)

// Asyncronous refresh session and ensure user is still logged in
supabaseClient?.auth.getSession().then(({ data: { session } }) => {
const setSupbaseUser = (session: Session) => {
if (session) {
if (JSON.stringify(supabaseUser.value) !== JSON.stringify(session.user)) {
supabaseUser.value = session.user
}
} else {
supabaseUser.value = null
}
}

// Asyncronous refresh session and ensure user is still logged in
supabaseClient?.auth.getSession().then(({ data: { session } }) => {
session && setSupbaseUser(session)
})

onMounted(async () => {
const { data: authListener } = supabaseClient.auth.onAuthStateChange(
async (event, newSession) => {
newSession && setSupbaseUser(newSession)
}
)

return () => {
authListener?.subscription.unsubscribe()
}
})

return {
Expand Down

0 comments on commit a297c62

Please sign in to comment.