2024-07-22 09:57:25 +08:00
|
|
|
import { QueryClient } from '@tanstack/react-query';
|
2024-07-11 11:00:51 +08:00
|
|
|
import { unstable_httpBatchStreamLink, loggerLink } from '@trpc/client';
|
2024-09-09 18:48:07 +08:00
|
|
|
import React, { useEffect, useMemo, useState } from 'react';
|
2024-07-11 11:00:51 +08:00
|
|
|
import { api } from '../utils/trpc';
|
|
|
|
import superjson from 'superjson';
|
2024-07-22 09:57:25 +08:00
|
|
|
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
|
|
|
|
import { createIDBPersister } from '../utils/idb';
|
2024-09-09 18:48:07 +08:00
|
|
|
import { env } from '../env';
|
|
|
|
import { useAuth } from './auth-provider';
|
2024-07-11 11:00:51 +08:00
|
|
|
export default function QueryProvider({ children }: { children: React.ReactNode }) {
|
|
|
|
const [queryClient] = useState(() => new QueryClient());
|
2024-09-09 18:48:07 +08:00
|
|
|
const { accessToken } = useAuth()
|
|
|
|
const trpcClient = useMemo(() =>
|
2024-07-11 11:00:51 +08:00
|
|
|
api.createClient({
|
|
|
|
links: [
|
|
|
|
unstable_httpBatchStreamLink({
|
2024-09-09 18:48:07 +08:00
|
|
|
url: `${env.API_URL}/trpc`,
|
|
|
|
headers: async () => ({
|
|
|
|
...(accessToken ? { 'Authorization': `Bearer ${accessToken}` } : {}),
|
|
|
|
}),
|
2024-07-11 11:00:51 +08:00
|
|
|
transformer: superjson
|
|
|
|
}),
|
|
|
|
loggerLink({
|
|
|
|
enabled: (opts) =>
|
|
|
|
(process.env.NODE_ENV === 'development' &&
|
|
|
|
typeof window !== 'undefined') ||
|
|
|
|
(opts.direction === 'down' && opts.result instanceof Error),
|
|
|
|
}),
|
|
|
|
],
|
2024-09-09 18:48:07 +08:00
|
|
|
}), [accessToken]
|
2024-07-11 11:00:51 +08:00
|
|
|
);
|
|
|
|
return (
|
|
|
|
<api.Provider client={trpcClient} queryClient={queryClient}>
|
2024-07-22 09:57:25 +08:00
|
|
|
<PersistQueryClientProvider client={queryClient} persistOptions={{ persister: createIDBPersister() }}>
|
2024-07-11 11:00:51 +08:00
|
|
|
{children}
|
2024-07-22 09:57:25 +08:00
|
|
|
</PersistQueryClientProvider>
|
2024-07-11 11:00:51 +08:00
|
|
|
</api.Provider>
|
|
|
|
);
|
|
|
|
}
|