|
1 | | -import type { FSMMachineConfig } from "@cicerchie/fsm"; |
2 | 1 | import type { Readable } from "svelte/store"; |
3 | 2 | import { newFSM } from "@cicerchie/fsm"; |
4 | 3 | import { writable } from "svelte/store"; |
5 | 4 |
|
6 | | -import { cache } from "./cache"; |
7 | | -import { decreaseFetching, increaseFetching } from "./indicator"; |
| 5 | +import { swrMachine } from "./machine"; |
8 | 6 |
|
9 | 7 | interface SWROptions<T> { |
10 | 8 | enabled?: boolean; |
@@ -46,66 +44,6 @@ const defaultSWRParams = { |
46 | 44 | }, |
47 | 45 | }; |
48 | 46 |
|
49 | | -const isEnabled = (_, event): boolean => event.data.options.enabled; |
50 | | - |
51 | | -const swrMachine: FSMMachineConfig = { |
52 | | - initial: "init", |
53 | | - on: { |
54 | | - revalidate: { |
55 | | - target: "revalidating", |
56 | | - cond: isEnabled, |
57 | | - }, |
58 | | - }, |
59 | | - states: { |
60 | | - init: {}, |
61 | | - revalidating: { |
62 | | - entry: (ctx, event) => { |
63 | | - if (cache.has(event.data.key)) { |
64 | | - ctx = { ...ctx, isLoading: false, data: cache.get(event.data.key) }; |
65 | | - } else if (event.data.options.initialData) { |
66 | | - const data = event.data.options.initialData(); |
67 | | - if (data) { |
68 | | - ctx = { ...ctx, isLoading: false, data }; |
69 | | - } |
70 | | - } |
71 | | - return { |
72 | | - ...ctx, |
73 | | - isLoading: !(ctx.data || ctx.error), |
74 | | - isFetching: true, |
75 | | - }; |
76 | | - }, |
77 | | - on: { |
78 | | - revalidate: null, |
79 | | - }, |
80 | | - invoke: { |
81 | | - src: (_, event) => { |
82 | | - increaseFetching(); |
83 | | - return event.data.fn(); |
84 | | - }, |
85 | | - onDone: { |
86 | | - target: "success", |
87 | | - action: (ctx, event) => { |
88 | | - cache.set(event.invokeEvent.data.key, event.data); |
89 | | - return { ...ctx, error: undefined, data: event.data }; |
90 | | - }, |
91 | | - }, |
92 | | - onError: { |
93 | | - target: "failure", |
94 | | - action: (ctx, event) => { |
95 | | - return { ...ctx, error: event.data, data: undefined }; |
96 | | - }, |
97 | | - }, |
98 | | - }, |
99 | | - exit: (ctx) => { |
100 | | - decreaseFetching(); |
101 | | - return { ...ctx, isLoading: false, isFetching: false }; |
102 | | - }, |
103 | | - }, |
104 | | - failure: {}, |
105 | | - success: {}, |
106 | | - }, |
107 | | -}; |
108 | | - |
109 | 47 | export function useSWR<T>(): SWRStore<T> { |
110 | 48 | // const store = writable<SWRStore<T>>({ ...defaultSWRStore }, () => { |
111 | 49 | // fsm.setEnabled(true); |
|
0 commit comments