Untitled
unknown
plain_text
2 years ago
1.9 kB
16
Indexable
export interface AuthContext {
session: Session | null | undefined;
user: User | null | undefined;
}
const AuthContext = createContext<AuthContext | null>(null);
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState<User>();
const [session, setSession] = useState<Session | null>();
useEffect(() => {
const setData = async () => {
const {
data: { session },
error,
} = await supabaseClient.auth.getSession();
if (error) throw error;
setSession(session);
setUser(session?.user);
};
const { data: listener } = supabaseClient.auth.onAuthStateChange((_event, session) => {
setSession(session);
setUser(session?.user);
});
setData();
return () => {
listener?.subscription.unsubscribe();
};
}, []);
const value = {
session,
user,
};
// use a provider to pass down the value
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
And then I do in main.tsx
// Set up a Router instance
const router = createRouter({
routeTree,
defaultPreload: 'intent',
context: {
auth: undefined!, // This will be set after we wrap the app in an AuthProvider
},
});
// Register things for typesafety
declare module '@tanstack/react-router' {
interface Register {
router: typeof router;
}
}
function InnerApp() {
const auth = useAuth();
return <RouterProvider router={router} context={{ auth }} />;
}
function App() {
return (
<AuthProvider>
<InnerApp />
</AuthProvider>
);
}`
export const Route = createFileRoute('/_authenticated')({
beforeLoad: async ({ context, location }) => {
console.log(context);Editor is loading...
Leave a Comment