Skip to content

Instantly share code, notes, and snippets.

@chadmuro
Last active August 31, 2023 23:03
Show Gist options
  • Save chadmuro/b1c398d68da90eeac70bf1ca01d4a822 to your computer and use it in GitHub Desktop.
Save chadmuro/b1c398d68da90eeac70bf1ca01d4a822 to your computer and use it in GitHub Desktop.
Supabase Auth Context
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);
};
@Lachezar14
Copy link

hi, when you refresh the page the user becomes null. any way to combat this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment