-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearchMachine.js
89 lines (83 loc) · 1.76 KB
/
searchMachine.js
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
import { useMachine } from "@xstate/react";
import React from "react";
import { createMachine, actions, assign } from "xstate";
const { send, cancel } = actions;
const DELAY = 500;
const searchMachine = createMachine(
{
id: "searchMachine",
initial: "idle",
strict: true,
context: {
phrase: "",
result: undefined
},
on: {
TYPE: {
actions: ["setPhrase", "cancelSearchEvent", "sendSearchEvent"]
},
SEARCH: {
target: ".searching"
}
},
states: {
idle: {},
searching: {
invoke: {
src: "search",
onDone: {
actions: "setResult",
target: "idle"
},
onError: {
target: "idle"
}
}
}
}
},
{
actions: {
sendSearchEvent: send(
{ type: "SEARCH" },
{ id: "searchEvent", delay: DELAY }
),
cancelSearchEvent: cancel("searchEvent"),
setPhrase: assign({
phrase: (_, event) => event.data
}),
setResult: assign({
result: (_, event) => event.data
})
},
services: {
search: async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.random());
}, 500);
});
}
}
}
);
export default function App() {
const [current, send] = useMachine(searchMachine);
const { phrase, result } = current.context;
return (
<div>
Result: <strong>{result}</strong>
<br />
State: <strong> {current.value}</strong>
<br />
<br />
<input
type="text"
value={phrase}
onChange={(event) => {
send({ type: "TYPE", data: event.target.value });
}}
/>
</div>
);
}