diff --git a/k-tv-frontend/app/providers.tsx b/k-tv-frontend/app/providers.tsx index 5a6f707..245c832 100644 --- a/k-tv-frontend/app/providers.tsx +++ b/k-tv-frontend/app/providers.tsx @@ -1,30 +1,49 @@ "use client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + QueryCache, + QueryClient, + QueryClientProvider, + MutationCache, +} from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { useState } from "react"; -import { AuthProvider } from "@/context/auth-context"; +import { useRouter } from "next/navigation"; +import { AuthProvider, useAuthContext } from "@/context/auth-context"; import { Toaster } from "@/components/ui/sonner"; +import { ApiRequestError } from "@/lib/api"; -export function Providers({ children }: { children: React.ReactNode }) { - const [queryClient] = useState( - () => - new QueryClient({ - defaultOptions: { - queries: { - staleTime: 60 * 1000, - }, - }, - }), - ); +function QueryProvider({ children }: { children: React.ReactNode }) { + const { setToken } = useAuthContext(); + const router = useRouter(); + + const [queryClient] = useState(() => { + const on401 = (error: unknown) => { + if (error instanceof ApiRequestError && error.status === 401) { + setToken(null); + router.push("/login"); + } + }; + return new QueryClient({ + queryCache: new QueryCache({ onError: on401 }), + mutationCache: new MutationCache({ onError: on401 }), + defaultOptions: { queries: { staleTime: 60 * 1000 } }, + }); + }); + return ( + + {children} + + + + ); +} + +export function Providers({ children }: { children: React.ReactNode }) { return ( - - {children} - - - + {children} ); }