Last active
August 31, 2023 23:03
-
-
Save chadmuro/b1c398d68da90eeac70bf1ca01d4a822 to your computer and use it in GitHub Desktop.
Supabase Auth Context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useContext, useState, useEffect, createContext } from 'react'; | |
import { supabase } from '../supabase'; | |
// create a context for authentication | |
const AuthContext = createContext(); | |
export const AuthProvider = ({ children }) => { | |
// create state values for user data and loading | |
const [user, setUser] = useState(); | |
const [loading, setLoading] = useState(true); | |
useEffect(() => { | |
// get session data if there is an active session | |
const session = supabase.auth.session(); | |
setUser(session?.user ?? null); | |
setLoading(false); | |
// listen for changes to auth | |
const { data: listener } = supabase.auth.onAuthStateChange( | |
(event, session) => { | |
setUser(session?.user ?? null); | |
setLoading(false); | |
} | |
); | |
// cleanup the useEffect hook | |
return () => { | |
listener?.unsubscribe(); | |
}; | |
}, []); | |
// create signUp, signIn, signOut functions | |
const value = { | |
signUp: data => supabase.auth.signUp(data), | |
signIn: data => supabase.auth.signIn(data), | |
signOut: () => supabase.auth.signOut(), | |
user, | |
}; | |
// use a provider to pass down the value | |
return ( | |
<AuthContext.Provider value={value}> | |
{!loading && children} | |
</AuthContext.Provider> | |
); | |
}; | |
// export the useAuth hook | |
export const useAuth = () => { | |
return useContext(AuthContext); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi, when you refresh the page the user becomes null. any way to combat this?