Skip to content

Comments

[@xstate/react] Expose error snapshots in useActor/useMachine#5456

Open
davidkpiano wants to merge 1 commit intomainfrom
5455-bug-cant-handle-errors-thrown-from-state-machine-in-react
Open

[@xstate/react] Expose error snapshots in useActor/useMachine#5456
davidkpiano wants to merge 1 commit intomainfrom
5455-bug-cant-handle-errors-thrown-from-state-machine-in-react

Conversation

@davidkpiano
Copy link
Member

useActor (and useMachine by alias) now properly re-renders when an action throws, exposing status: 'error' and error on the snapshot.

const App = () => {
  // Machine that might throw an error, e.g.:
  // entry: () => throw new Error('error');
  const [state, send, actor] = useActor(machine);

  const errorMessage = state.status === 'error' ? (state.error as Error)?.message : null;
  
  // ...
};

Fixes #5455

@davidkpiano davidkpiano linked an issue Jan 22, 2026 that may be closed by this pull request
@changeset-bot
Copy link

changeset-bot bot commented Jan 22, 2026

🦋 Changeset detected

Latest commit: c17371a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@xstate/react Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@davidkpiano davidkpiano changed the title Expose error snapshots in useActor/useMachine [@xstate/react] Expose error snapshots in useActor/useMachine Jan 22, 2026
@davidkpiano davidkpiano requested a review from Andarist January 22, 2026 12:53
const subscribe = useCallback(
(handleStoreChange: () => void) => {
const { unsubscribe } = actorRef.subscribe(handleStoreChange);
const { unsubscribe } = actorRef.subscribe({
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldnt this also have complete: handleStoreChange?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this might sound controversial but I'd consider doing this in the useActor's implementation:

if (actorSnapshot.status === 'error') throw actorSnapshot.error;

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not opposed to this 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Can't handle errors thrown from state machine in React

2 participants