-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseIsXStateTransitionAvailable.ts
51 lines (49 loc) · 1.7 KB
/
useIsXStateTransitionAvailable.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
import { useCallback } from 'react';
import { ActorRef, EventObject, StateMachine, Interpreter } from 'xstate';
import { useSelector } from '@xstate/react';
/**
* @deprecated depricated in favor of useStateCan()
*/
export function useIsXStateTransitionAvailable<
TEventType extends TEvent['type'],
TEvent extends EventObject = EventObject,
>(service: Interpreter<any, any, TEvent, any>, event: TEventType | TEvent): boolean;
export function useIsXStateTransitionAvailable<
TEventType extends TEvent['type'],
TEvent extends EventObject = EventObject,
>(
service: ActorRef<TEvent> & { machine?: StateMachine<any, any, TEvent, any> },
event: TEventType | TEvent,
): boolean;
export function useIsXStateTransitionAvailable<
TEventType extends TEvent['type'],
TEvent extends EventObject = EventObject,
>(
service:
| Interpreter<any, any, TEvent, any>
| (ActorRef<TEvent> & { machine?: StateMachine<any, any, TEvent, any> }),
event: TEventType | TEvent,
): boolean {
if (
// Machines invoked as services will be initially deferred:
// https://github.com/statelyai/xstate/blob/5da8724bb6c4dada5d6e8cc61e36c7e2c771838b/packages/core/src/Actor.ts#L74-L94
//
// Because we don't know what a deferred service will initialize to,
// we shouldn't throw if it doesn't have a "machine" property
//
// @ts-ignore
!service.deferred &&
!service.machine
) {
throw new Error(
'The service given to useIsXStateTransitionAvailable() must be a state machine instance.',
);
}
return useSelector<typeof service, boolean>(
service,
useCallback(
state => !!service.machine && !!service.machine!.transition(state, event).changed,
[service, event],
),
);
}