-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathQueryClientProvider.tsx
More file actions
177 lines (160 loc) · 5.24 KB
/
QueryClientProvider.tsx
File metadata and controls
177 lines (160 loc) · 5.24 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import { MissingRedmineConfigError } from "@/api/redmine/MissingRedmineConfigError";
import { getErrorMessage } from "@/utils/error";
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
import { MutationCache, QueryCache, QueryClient, useIsRestoring } from "@tanstack/react-query";
import { PersistQueryClientOptions, PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
import { isAxiosError } from "axios";
import { lazy, PropsWithChildren, Suspense, useEffect } from "react";
import { FormattedMessage } from "react-intl";
import { toast } from "sonner";
import { browser } from "wxt/browser";
import { useStorage } from "../hooks/useStorage";
declare module "@tanstack/react-query" {
interface Register {
queryMeta: {
/**
* Should display an error toast when the query fails
*
* @default true
*/
displayErrorToast?: boolean;
};
mutationMeta: {
/**
* Should display a success toast when the mutation succeeds
*/
successMessage?: string;
};
}
}
const CACHE_TIME = 1000 * 60 * 60 * 24; // 24 hours
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: CACHE_TIME,
staleTime: 1000 * 60 * 60, // 1 hour
retry: 1,
},
},
queryCache: new QueryCache({
onError: (error, query) => {
if (query.meta?.displayErrorToast === false) return;
// Skip if Redmine URL is not configured
if (error instanceof MissingRedmineConfigError) return;
if (!isAxiosError(error)) {
toast.error(
<FormattedMessage
id="general.error.unknown-error"
values={{
name: error.name,
}}
/>,
{
description: getErrorMessage(error),
closeButton: true,
duration: 1000 * 60, // 1 minute
}
);
return;
}
const failedQueries = queryClient
.getQueryCache()
.getAll()
.filter((q) => q.state.error && isAxiosError(q.state.error) && q.meta?.displayErrorToast !== false);
toast.error(<FormattedMessage id="general.error.api-error" />, {
id: "api-error",
description: Object.entries(
failedQueries.reduce((errors: Record<string, number>, q) => {
const message = getErrorMessage(q.state.error);
if (message) errors[message] = (errors[message] ?? 0) + 1;
return errors;
}, {})
).map(([msg, count]) => (
<p key={msg}>
{msg}
{count > 1 ? ` (${count}x)` : null}
</p>
)),
action: {
label: <FormattedMessage id="general.retry" />,
onClick: () => {
failedQueries.forEach((q) => {
queryClient.refetchQueries({ queryKey: q.queryKey, exact: true });
});
},
},
closeButton: true,
duration: 1000 * 60, // 1 minute
});
},
}),
mutationCache: new MutationCache({
onSuccess: (_data, _variables, _context, mutation) => {
if (mutation.meta?.successMessage) {
toast.success(mutation.meta.successMessage);
}
},
onError: (error) => {
const title = isAxiosError(error) ? (
<FormattedMessage id="general.error.api-error" />
) : (
<FormattedMessage
id="general.error.unknown-error"
values={{
name: error.name,
}}
/>
);
toast.error(title, {
description: getErrorMessage(error),
closeButton: true,
duration: 1000 * 60 * 5, // 5 minutes
});
},
}),
});
const persister = createAsyncStoragePersister({
storage: {
getItem: async (key) => (await browser.storage.local.get<Record<string, string>>(key))[key],
setItem: (key, value) => browser.storage.local.set({ [key]: value }),
removeItem: (key) => browser.storage.local.remove(key),
},
throttleTime: 1000,
});
const persistOptions: Omit<PersistQueryClientOptions, "queryClient"> = {
buster: browser.runtime.getManifest().version,
persister,
maxAge: CACHE_TIME,
};
const QueryClientProvider = ({ children }: PropsWithChildren) => {
return (
<PersistQueryClientProvider client={queryClient} persistOptions={persistOptions}>
<QueryClientRestoringGate>{children}</QueryClientRestoringGate>
<QueryClientDevtools />
</PersistQueryClientProvider>
);
};
const QueryClientRestoringGate = ({ children }: PropsWithChildren) => {
const isRestoring = useIsRestoring();
return isRestoring ? null : children;
};
const ReactQueryDevtoolsProduction = lazy(() =>
import("@tanstack/react-query-devtools/build/modern/production.js").then((d) => ({
default: d.ReactQueryDevtools,
}))
);
const QueryClientDevtools = () => {
const { data: showDevtools, setData: setShowDevtools } = useStorage("tanstackQueryDevtools", false);
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
window.toggleDevtools = () => setShowDevtools(!showDevtools);
}, [showDevtools, setShowDevtools]);
if (!showDevtools) return null;
return (
<Suspense fallback={null}>
<ReactQueryDevtoolsProduction />
</Suspense>
);
};
export default QueryClientProvider;