-
Notifications
You must be signed in to change notification settings - Fork 0
/
queryClient.ts
47 lines (43 loc) · 1.25 KB
/
queryClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { QueryClient, type QueryFilters } from "@tanstack/react-query";
import {
type PersistedQuery,
experimental_createPersister
} from "@tanstack/react-query-persist-client";
import { del, get, set } from "idb-keyval";
import { ONE_DAY_IN_MILLIS } from "./constants";
const cachedQueryKeys = new Set([
"budgets",
"payees",
"categoryGroups",
"accounts",
"import"
]);
export const createQueryClient = (options?: { staleTime?: number }) =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: options?.staleTime,
retry: 1, // only retry once if there's an error,
persister: createIdbPersister("ynab", {
predicate: ({ queryKey }) =>
typeof queryKey[0] === "string" && cachedQueryKeys.has(queryKey[0])
})
}
}
});
/** Creates an Indexed DB persister for React Query */
function createIdbPersister(prefix: string, filters: QueryFilters) {
return experimental_createPersister<PersistedQuery>({
prefix,
filters,
maxAge: ONE_DAY_IN_MILLIS * 7,
storage: {
getItem: (key) => get(key),
setItem: (key, val) => set(key, val),
removeItem: (key) => del(key)
},
serialize: (query) => query,
deserialize: (query) => query,
buster: "v2"
});
}