Skip to content

Commit

Permalink
Add AuthContext
Browse files Browse the repository at this point in the history
  • Loading branch information
adityapawar1 committed Oct 7, 2023
1 parent d9cf4b5 commit 94fcbee
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/app/_layout.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Stack } from 'expo-router';
import { AuthContextProvider } from '../utils/AuthContext';

function StackLayout() {
return (
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="settings" options={{ headerShown: false }} />
<Stack.Screen name="auth" options={{ headerShown: false }} />
</Stack>
<AuthContextProvider>
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="settings" options={{ headerShown: false }} />
<Stack.Screen name="auth" options={{ headerShown: false }} />
</Stack>
</AuthContextProvider>
);
}

Expand Down
75 changes: 75 additions & 0 deletions src/utils/AuthContext.tsx
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>
);
}

0 comments on commit 94fcbee

Please sign in to comment.