-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathuseActor.ts
75 lines (66 loc) · 1.86 KB
/
useActor.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
import isDevelopment from '#is-development';
import { useCallback, useEffect } from 'react';
import { useSyncExternalStore } from 'use-sync-external-store/shim';
import {
Actor,
ActorOptions,
AnyActorLogic,
Snapshot,
SnapshotFrom,
type ConditionalRequired,
type IsNotNever,
type RequiredActorOptionsKeys
} from 'xstate';
import { stopRootWithRehydration } from './stopRootWithRehydration.ts';
import { useIdleActorRef } from './useActorRef.ts';
export function useActor<TLogic extends AnyActorLogic>(
logic: TLogic,
...[options]: ConditionalRequired<
[
options?: ActorOptions<TLogic> & {
[K in RequiredActorOptionsKeys<TLogic>]: unknown;
}
],
IsNotNever<RequiredActorOptionsKeys<TLogic>>
>
): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>] {
if (
isDevelopment &&
!!logic &&
'send' in logic &&
typeof logic.send === 'function'
) {
throw new Error(
`useActor() expects actor logic (e.g. a machine), but received an ActorRef. Use the useSelector(actorRef, ...) hook instead to read the ActorRef's snapshot.`
);
}
const actorRef = useIdleActorRef(logic, options);
const getSnapshot = useCallback(() => {
return actorRef.getSnapshot();
}, [actorRef]);
const subscribe = useCallback(
(handleStoreChange: () => void) => {
const { unsubscribe } = actorRef.subscribe(
handleStoreChange,
handleStoreChange
);
return unsubscribe;
},
[actorRef]
);
const actorSnapshot = useSyncExternalStore(
subscribe,
getSnapshot,
getSnapshot
);
if ((actorSnapshot as Snapshot<any>).status === 'error') {
throw (actorSnapshot as Snapshot<any>).error;
}
useEffect(() => {
actorRef.start();
return () => {
stopRootWithRehydration(actorRef);
};
}, [actorRef]);
return [actorSnapshot, actorRef.send, actorRef];
}