-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (84 loc) · 2.52 KB
/
index.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
import { Machine, assign } from 'xstate';
import { useMachine } from '@xstate/react';
const requestMachine = Machine({
id: 'request',
context: {
buttonName: '',
readyName: '',
loadingName: '',
buttonDisabled: false
},
initial: 'ready',
states: {
ready: {
on: {
REQUEST: {
target: 'loading',
actions: assign((context, event) => {
return {
buttonName: context.loadingName,
buttonDisabled: true
}
})
}
}
},
loading: {
invoke: {
src: 'request',
onDone: {
target: 'ready',
actions: assign((context, event) => {
return {
buttonName: context.readyName,
buttonDisabled: false
}
})
}
}
}
}
});
const isSet = (value) => value !== null && value !== undefined;
export const useXstateForButton = (request, config) => {
if (!isSet(request)) {
console.error('useXstateForButton: request not specified');
return [];
}
if (typeof request !== 'function') {
console.error('useXstateForButton: request must be a function');
return [];
}
if (!isSet(config) || typeof config !== 'object')
config = {};
let readyName = config.readyName;
let loadingName = config.loadingName;
if (!isSet(readyName))
readyName = 'Button';
if (!isSet(loadingName))
loadingName = 'Loading...';
let promise;
if (config.promise === true)
promise = async (context, event) => new Promise((resolve, reject) => request(context, event, resolve));
else
promise = request;
const myRequestMachine = requestMachine.withContext({
buttonName: readyName,
readyName,
loadingName
});
const [state, send] = useMachine(myRequestMachine, {
services: {
request: promise
}
});
const buttonName = state.context.buttonName;
const buttonDisabled = state.context.buttonDisabled;
const start = (params) => {
if (isSet(params) && config.noParams !== true)
send('REQUEST', params);
else
send('REQUEST');
};
return [start, buttonName, buttonDisabled];
};