feat: refactor QueryProvider to include error handling and improve query client setup
This commit is contained in:
@@ -1,30 +1,49 @@
|
|||||||
"use client";
|
"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 { ReactQueryDevtools } from "@tanstack/react-query-devtools";
|
||||||
import { useState } from "react";
|
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 { Toaster } from "@/components/ui/sonner";
|
||||||
|
import { ApiRequestError } from "@/lib/api";
|
||||||
|
|
||||||
export function Providers({ children }: { children: React.ReactNode }) {
|
function QueryProvider({ children }: { children: React.ReactNode }) {
|
||||||
const [queryClient] = useState(
|
const { setToken } = useAuthContext();
|
||||||
() =>
|
const router = useRouter();
|
||||||
new QueryClient({
|
|
||||||
defaultOptions: {
|
const [queryClient] = useState(() => {
|
||||||
queries: {
|
const on401 = (error: unknown) => {
|
||||||
staleTime: 60 * 1000,
|
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 (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
{children}
|
||||||
|
<Toaster position="bottom-right" richColors />
|
||||||
|
<ReactQueryDevtools initialIsOpen={false} />
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Providers({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryProvider>{children}</QueryProvider>
|
||||||
{children}
|
|
||||||
<Toaster position="bottom-right" richColors />
|
|
||||||
<ReactQueryDevtools initialIsOpen={false} />
|
|
||||||
</QueryClientProvider>
|
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user