-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d9cf4b5
commit 94fcbee
Showing
2 changed files
with
83 additions
and
5 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import { Session } from '@supabase/supabase-js'; | ||
import React, { createContext, useContext, useEffect, useReducer } from 'react'; | ||
import supabase from './supabase'; | ||
|
||
export interface AuthState { | ||
session: Session | null; | ||
} | ||
enum AuthActionType { | ||
SIGN_IN, | ||
SIGN_OUT, | ||
} | ||
type AuthContextAction = | ||
| { type: AuthActionType.SIGN_IN; session: Session } | ||
| { type: AuthActionType.SIGN_OUT }; | ||
|
||
const AuthContext = createContext({} as AuthState); | ||
export const useAuthContext = () => useContext(AuthContext); | ||
|
||
const useAuthReducer = () => | ||
useReducer( | ||
(prevState: AuthState, action: AuthContextAction) => { | ||
switch (action.type) { | ||
case AuthActionType.SIGN_IN: | ||
return { | ||
session: action.session, | ||
}; | ||
case AuthActionType.SIGN_OUT: | ||
return { | ||
session: null, | ||
}; | ||
default: | ||
return prevState; | ||
} | ||
}, | ||
{ session: null }, | ||
); | ||
|
||
export function useSession() { | ||
const value = React.useContext(AuthContext); | ||
if (process.env.NODE_ENV !== 'production') { | ||
if (!value) { | ||
throw new Error('useSession must be wrapped in a <SessionProvider />'); | ||
} | ||
} | ||
|
||
return value; | ||
} | ||
|
||
export function AuthContextProvider({ | ||
children, | ||
}: { | ||
children: React.ReactNode; | ||
}) { | ||
const [authState, dispatch] = useAuthReducer(); | ||
|
||
useEffect(() => { | ||
supabase.auth.getSession().then(({ data: { session: newSession } }) => { | ||
if (newSession) { | ||
dispatch({ type: AuthActionType.SIGN_IN, session: newSession }); | ||
} | ||
}); | ||
|
||
supabase.auth.onAuthStateChange((_event, newSession) => { | ||
if (newSession) { | ||
dispatch({ type: AuthActionType.SIGN_IN, session: newSession }); | ||
} | ||
}); | ||
}, []); | ||
|
||
return ( | ||
<AuthContext.Provider value={{} as AuthState}> | ||
{children} | ||
</AuthContext.Provider> | ||
); | ||
} |