UNPKG

1.74 kBJavaScriptView Raw
1import { atomsWithQuery, queryClientAtom, atomsWithInfiniteQuery } from 'jotai-tanstack-query';
2export { queryClientAtom } from 'jotai-tanstack-query';
3import { atom } from 'jotai';
4
5function atomWithQuery(createQuery, getQueryClient = (get) => get(queryClientAtom)) {
6 const getOptions = (get) => ({
7 staleTime: 200,
8 ...typeof createQuery === "function" ? createQuery(get) : createQuery
9 });
10 const [dataAtom] = atomsWithQuery(getOptions, getQueryClient);
11 return atom(
12 (get) => {
13 const options = getOptions(get);
14 if (options.enabled === false) {
15 const queryClient = getQueryClient(get);
16 return queryClient.getQueryData(options.queryKey);
17 }
18 return get(dataAtom);
19 },
20 (_get, set, action) => {
21 if (action.type === "refetch") {
22 return set(dataAtom, { type: "refetch", force: true });
23 }
24 }
25 );
26}
27
28function atomWithInfiniteQuery(createQuery, getQueryClient = (get) => get(queryClientAtom)) {
29 const getOptions = (get) => ({
30 staleTime: 200,
31 ...typeof createQuery === "function" ? createQuery(get) : createQuery
32 });
33 const [dataAtom] = atomsWithInfiniteQuery(getOptions, getQueryClient);
34 return atom(
35 (get) => {
36 const options = getOptions(get);
37 if (options.enabled === false) {
38 const queryClient = getQueryClient(get);
39 return queryClient.getQueryData(options.queryKey);
40 }
41 return get(dataAtom);
42 },
43 (_get, set, action) => {
44 if (action.type === "refetch") {
45 return set(dataAtom, {
46 type: "refetch",
47 force: true,
48 options: action.payload
49 });
50 }
51 return set(dataAtom, action);
52 }
53 );
54}
55
56export { atomWithInfiniteQuery, atomWithQuery };