-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathindex.tsx
77 lines (73 loc) · 2 KB
/
index.tsx
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
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import useStateMachine, {t} from '@cassiozen/usestatemachine';
import { checkUsernameAvailability } from './fakeForm';
import './index.css';
/*
* In this example we use events with payload to send data from the form to the state machine
*/
function App() {
const [machine, send] = useStateMachine({
schema: {
context: t<{ input: string }>(),
events: {
UPDATE: t<{ value: string }>()
}
},
context: {input: ''},
verbose: true,
initial: 'pristine',
states: {
pristine: {},
editing: {
on: {
VALIDATE: 'validating',
},
effect({ send, setContext, event }) {
setContext(c => ({ input: event?.value ?? '' }));
const timeout = setTimeout(() => {
send({ type: 'VALIDATE' });
}, 300);
return () => clearTimeout(timeout);
},
},
validating: {
on: {
VALID: 'valid',
INVALID: 'invalid',
},
effect({ send, context }) {
checkUsernameAvailability(context.input).then(usernameAvailable => {
if (usernameAvailable) send('VALID');
else send('INVALID');
});
},
},
valid: {},
invalid: {},
},
on: {
UPDATE: 'editing',
},
});
return (
<div className="usernameForm">
<form>
<input
type="text"
placeholder="Choose an username"
aria-label="Choose an username"
value={machine.context.input}
onChange={e => send({ type: 'UPDATE', value: e.target.value })}
/>
{machine.value === 'validating' && <div className="loader" />}
{machine.value === 'valid' && '✔'}
{machine.value === 'invalid' && '❌'}
<button type="submit" disabled={machine.value !== 'valid'}>
Create User
</button>
</form>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));