* docs(react-native): create the basic expo project * docs(react-native): cross-platform Apple social sign-in * docs(react-native): cross-platform Google social sign-in * docs(react-native): fix typos * docs(react-native): remove wrong entry in the `Connection` component * Correct typos * Prettier * Draft * Draft * docs(react-native): use kebab-case file naming convention in Expo guide - use kebab-case file naming convention in Expo guide - add trailing semicolon to align with the standard Expo template conventions * docs(react-native): use kebab-case file naming convention in Expo social auth example * docs(react-native): update the packages of the Expo social auth example * Fix * Draft * Changes * Correct log message --------- Co-authored-by: Chris Chinchilla <chris.ward@supabase.io> Co-authored-by: Chris Chinchilla <chris@chrischinchilla.com>
75 lines
1.8 KiB
TypeScript
75 lines
1.8 KiB
TypeScript
import { AuthContext } from '@/hooks/use-auth-context'
|
|
import { supabase } from '@/lib/supabase'
|
|
import type { Session } from '@supabase/supabase-js'
|
|
import { PropsWithChildren, useEffect, useState } from 'react'
|
|
|
|
export default function AuthProvider({ children }: PropsWithChildren) {
|
|
const [session, setSession] = useState<Session | undefined | null>()
|
|
const [profile, setProfile] = useState<any>()
|
|
const [isLoading, setIsLoading] = useState<boolean>(true)
|
|
|
|
// Fetch the session once, and subscribe to auth state changes
|
|
useEffect(() => {
|
|
const fetchSession = async () => {
|
|
setIsLoading(true)
|
|
|
|
const { data: { session }, error } = await supabase.auth.getSession()
|
|
|
|
if (error) {
|
|
console.error('Error fetching session:', error)
|
|
}
|
|
|
|
setSession(session)
|
|
setIsLoading(false)
|
|
}
|
|
|
|
fetchSession()
|
|
|
|
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
|
|
console.log('Auth state changed:', { event: _event, session })
|
|
setSession(session)
|
|
})
|
|
|
|
// Cleanup subscription on unmount
|
|
return () => {
|
|
subscription.unsubscribe()
|
|
}
|
|
}, [])
|
|
|
|
// Fetch the profile when the session changes
|
|
useEffect(() => {
|
|
const fetchProfile = async () => {
|
|
setIsLoading(true)
|
|
|
|
if (session) {
|
|
const { data } = await supabase
|
|
.from('profiles')
|
|
.select('*')
|
|
.eq('id', session.user.id)
|
|
.single()
|
|
|
|
setProfile(data)
|
|
} else {
|
|
setProfile(null)
|
|
}
|
|
|
|
setIsLoading(false)
|
|
}
|
|
|
|
fetchProfile()
|
|
}, [session])
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{
|
|
session,
|
|
isLoading,
|
|
profile,
|
|
isLoggedIn: session != undefined
|
|
}}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
)
|
|
}
|