2023-06-15 12:52:46 +03:00
|
|
|
"use client";
|
2023-05-24 17:17:08 +03:00
|
|
|
|
2023-06-15 12:52:46 +03:00
|
|
|
import type { SupabaseClient } from "@supabase/auth-helpers-nextjs";
|
|
|
|
import {
|
|
|
|
createBrowserSupabaseClient,
|
|
|
|
Session,
|
|
|
|
} from "@supabase/auth-helpers-nextjs";
|
|
|
|
import { useRouter } from "next/navigation";
|
|
|
|
import { createContext, useContext, useEffect, useState } from "react";
|
2023-05-24 17:17:08 +03:00
|
|
|
|
2023-06-15 12:52:46 +03:00
|
|
|
type MaybeSession = Session | null;
|
2023-05-24 17:17:08 +03:00
|
|
|
|
2023-06-20 17:17:13 +03:00
|
|
|
export type SupabaseContext = {
|
2023-06-15 12:52:46 +03:00
|
|
|
supabase: SupabaseClient;
|
|
|
|
session: MaybeSession;
|
|
|
|
};
|
2023-05-24 17:17:08 +03:00
|
|
|
|
2023-06-15 12:52:46 +03:00
|
|
|
const Context = createContext<SupabaseContext | undefined>(undefined);
|
2023-05-24 17:17:08 +03:00
|
|
|
|
2023-06-20 17:17:13 +03:00
|
|
|
export const SupabaseProvider = ({
|
2023-05-24 17:17:08 +03:00
|
|
|
children,
|
|
|
|
session,
|
|
|
|
}: {
|
2023-06-15 12:52:46 +03:00
|
|
|
children: React.ReactNode;
|
|
|
|
session: MaybeSession;
|
|
|
|
}): JSX.Element => {
|
|
|
|
const [supabase] = useState(() => createBrowserSupabaseClient());
|
|
|
|
const router = useRouter();
|
2023-05-24 17:17:08 +03:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const {
|
|
|
|
data: { subscription },
|
|
|
|
} = supabase.auth.onAuthStateChange(() => {
|
2023-06-15 12:52:46 +03:00
|
|
|
router.refresh();
|
|
|
|
});
|
2023-05-24 17:17:08 +03:00
|
|
|
|
|
|
|
return () => {
|
2023-06-15 12:52:46 +03:00
|
|
|
subscription.unsubscribe();
|
|
|
|
};
|
|
|
|
}, [router, supabase]);
|
2023-05-24 17:17:08 +03:00
|
|
|
|
|
|
|
return (
|
|
|
|
<Context.Provider value={{ supabase, session }}>
|
|
|
|
<>{children}</>
|
|
|
|
</Context.Provider>
|
2023-06-15 12:52:46 +03:00
|
|
|
);
|
|
|
|
};
|
2023-05-24 17:17:08 +03:00
|
|
|
|
2023-06-15 12:52:46 +03:00
|
|
|
export const useSupabase = (): SupabaseContext => {
|
|
|
|
const context = useContext(Context);
|
2023-05-24 17:17:08 +03:00
|
|
|
|
|
|
|
if (context === undefined) {
|
2023-06-15 12:52:46 +03:00
|
|
|
throw new Error("useSupabase must be used inside SupabaseProvider");
|
2023-05-24 17:17:08 +03:00
|
|
|
}
|
|
|
|
|
2023-06-15 12:52:46 +03:00
|
|
|
return context;
|
|
|
|
};
|