-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearchMachineWithTypescript.ts
105 lines (97 loc) · 2.06 KB
/
searchMachineWithTypescript.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
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
import * as React from "react";
import { useMachine } from "@xstate/react";
import { assign, createMachine, send, actions, DoneInvokeEvent } from "xstate";
type TypeEvent = {
type: "TYPE";
data: string;
};
type SearchEvent = {
type: "SEARCH";
data: undefined;
};
type Event = TypeEvent | SearchEvent;
type Context = {
phrase: string;
result: number | undefined;
};
const { cancel } = actions;
const DELAY = 1000;
const searchMachine = createMachine<Context, Event>(
{
id: "search",
initial: "idle",
context: {
phrase: "",
result: undefined
},
on: {
TYPE: {
actions: ["setPhrase", "cancelSeaachEvent", "sendSearchEvent"]
},
SEARCH: {
target: ".searching"
}
},
states: {
idle: {},
searching: {
invoke: {
src: "search",
onDone: {
actions: "setResult",
target: "idle"
},
onError: {
target: "idle"
}
}
}
}
},
{
actions: {
setPhrase: assign<Context, TypeEvent>({
phrase: (_, event) => event.data
}),
sendSearchEvent: send(
{ type: "SEARCH" },
{
id: "searchEvent",
delay: DELAY
}
),
setResult: assign<Context, DoneInvokeEvent<number>>({
result: (_, event) => event.data
}),
cancelSeaachEvent: cancel("searchEvent")
} as any,
services: {
search: async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Math.random());
}, 1000);
});
}
}
}
);
export default function App() {
const [current, send] = useMachine(searchMachine);
const { result, phrase } = current.context;
return (
<div>
Result: <strong>{result}</strong>
<br />
State: <strong>{current.value}</strong>
<br />
<br />
<input
value={phrase}
onChange={(event) => {
send({ type: "TYPE", data: event.target.value });
}}
/>
</div>
);
}