-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
45 lines (40 loc) · 1.16 KB
/
index.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
import { makeAutoObservable, onBecomeObserved } from "mobx"
export class WithQuery<TData, TResult = TData> {
constructor(
private method: (...args: any) => Promise<TData>,
private config?: {
loadOnMount?: boolean
onError?: () => void
onSuccess?: (data: TData) => void
transform?: (data: TData) => TResult
},
) {
makeAutoObservable(this)
this.config = { loadOnMount: true, ...this.config }
if (this.config.loadOnMount) onBecomeObserved(this, "data", this.load)
}
isLoading?: boolean
started = false
state: "fulfilled" | "pending" | "rejected" = "pending"
data?: TResult = undefined
error?: unknown
load = async (...args: any) => {
try {
this.started = true
this.isLoading = true
const result = await this.method(args)
this.data = this.config?.transform
? this.config.transform(result)
: (result as TResult)
this.state = "fulfilled"
this.config?.onSuccess?.(result)
} catch (error) {
this.error = error
this.state = "rejected"
this.config?.onError?.()
} finally {
this.isLoading = false
return this.data as TData
}
}
}