better supabase auth than with useEffect & getSession on each page?

apparently the way i was doing this was very noob, but not sure what the best alternative would be before i had a useEffect on each page in my webapp like this
useEffect(() => {
const getUser = async () => {
const {
data: { session },
} = await supabase.auth.getSession()

if (!session) {
console.log('no session')
} else if (!session.user) {
console.log('no user')
} else {
// console.log('session.user: ', session.user)
setUser(session.user)
}
}

void getUser()
}, [])
useEffect(() => {
const getUser = async () => {
const {
data: { session },
} = await supabase.auth.getSession()

if (!session) {
console.log('no session')
} else if (!session.user) {
console.log('no user')
} else {
// console.log('session.user: ', session.user)
setUser(session.user)
}
}

void getUser()
}, [])
apparently this is really bad, especially on each page. what should i be doing instead when using supabase auth? id like to have the session/user data and details available on every page without have the same useeffect call on every page
7 Replies
oadster
oadster2y ago
You can do something like create a hook / auth context
oadster
oadster2y ago
Gist
Supabase Auth Context
Supabase Auth Context. GitHub Gist: instantly share code, notes, and snippets.
oadster
oadster2y ago
Another guide
oadster
oadster2y ago
Authentication with Supabase and React
Supabase is an open source managed backend platform. It's a direct alternative Firebase, which is owned by Google...
oadster
oadster2y ago
It is more or less the same But you aren’t doing your useEffect fetch for every page
Domcario
DomcarioOP2y ago
yea idk useUser seems broken, always returns null. there's a lot of posts in the supabase discord and the supabase-js github discussion about it maybe ill just switch to nextauth
Want results from more Discord servers?
Add your server