forked from isaacplmann/sturdy-uis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.ts
More file actions
88 lines (84 loc) · 1.86 KB
/
fetch.ts
File metadata and controls
88 lines (84 loc) · 1.86 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
import { assign, Machine } from 'xstate';
// The hierarchical (recursive) schema for the states
interface FetchSchema {
states: {
idle: {};
pending: {};
fulfilled: {
states: {
unknown: {};
withData: {};
withoutData: {};
};
};
rejected: {};
};
}
// The events that the machine handles
type ResolveEvent = { type: 'RESOLVE'; results: any[] };
type RejectEvent = { type: 'REJECT'; message: string };
type FetchEvents = { type: 'FETCH' } | ResolveEvent | RejectEvent;
// The context (extended state) of the machine
interface FetchContext {
results?: any[];
message?: string;
}
export const fetchMachine = Machine<FetchContext, FetchSchema, FetchEvents>(
{
id: 'fetch',
initial: 'idle',
context: {},
states: {
idle: {
on: { FETCH: 'pending' }
},
pending: {
entry: ['fetchData'],
on: {
RESOLVE: { target: 'fulfilled' },
REJECT: { target: 'rejected' }
}
},
fulfilled: {
entry: ['setResults'],
on: {
FETCH: 'pending'
},
initial: 'unknown',
states: {
unknown: {
on: {
'': [
{ target: 'withData', cond: 'hasData' },
{ target: 'withoutData' }
]
}
},
withData: {
entry: ['notifyHasData']
},
withoutData: {}
}
},
rejected: {
entry: ['setMessage'],
on: {
FETCH: 'pending'
}
}
}
},
{
actions: {
setResults: assign((ctx, event: any) => ({
results: event.results
})),
setMessage: assign((ctx, event: any) => ({
message: event.message
}))
},
guards: {
hasData: (ctx, event) => !!ctx.results && ctx.results.length > 0
}
}
);