(
logic: TLogic,
...[options]: ConditionalRequired<
[
options?: ActorOptions<TLogic> & {
[K in RequiredActorOptionsKeys<TLogic>]: unknown;
}
],
IsNotNever<RequiredActorOptionsKeys<TLogic>>
>
)
| 15 | import { useIdleActorRef } from './useActorRef.ts'; |
| 16 | |
| 17 | export function useActor<TLogic extends AnyActorLogic>( |
| 18 | logic: TLogic, |
| 19 | ...[options]: ConditionalRequired< |
| 20 | [ |
| 21 | options?: ActorOptions<TLogic> & { |
| 22 | [K in RequiredActorOptionsKeys<TLogic>]: unknown; |
| 23 | } |
| 24 | ], |
| 25 | IsNotNever<RequiredActorOptionsKeys<TLogic>> |
| 26 | > |
| 27 | ): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>] { |
| 28 | if ( |
| 29 | isDevelopment && |
| 30 | !!logic && |
| 31 | 'send' in logic && |
| 32 | typeof logic.send === 'function' |
| 33 | ) { |
| 34 | throw new Error( |
| 35 | `useActor() expects actor logic (e.g. a machine), but received an ActorRef. Use the useSelector(actorRef, ...) hook instead to read the ActorRef's snapshot.` |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | const actorRef = useIdleActorRef(logic, options); |
| 40 | |
| 41 | const getSnapshot = useCallback(() => { |
| 42 | return actorRef.getSnapshot(); |
| 43 | }, [actorRef]); |
| 44 | |
| 45 | const subscribe = useCallback( |
| 46 | (handleStoreChange: () => void) => { |
| 47 | const { unsubscribe } = actorRef.subscribe({ |
| 48 | next: handleStoreChange, |
| 49 | error: handleStoreChange |
| 50 | }); |
| 51 | return unsubscribe; |
| 52 | }, |
| 53 | [actorRef] |
| 54 | ); |
| 55 | |
| 56 | const actorSnapshot = useSyncExternalStore( |
| 57 | subscribe, |
| 58 | getSnapshot, |
| 59 | getSnapshot |
| 60 | ); |
| 61 | |
| 62 | const snapshotWithStatus = |
| 63 | 'status' in actorSnapshot |
| 64 | ? (actorSnapshot as Snapshot<unknown>) |
| 65 | : undefined; |
| 66 | if (snapshotWithStatus?.status === 'error') { |
| 67 | throw snapshotWithStatus.error; |
| 68 | } |
| 69 | |
| 70 | useEffect(() => { |
| 71 | actorRef.start(); |
| 72 | |
| 73 | return () => { |
| 74 | stopRootWithRehydration(actorRef); |
searching dependent graphs…