Skip to content

Instantly share code, notes, and snippets.

@yarigpopov
Created October 15, 2021 22:13
Show Gist options
  • Save yarigpopov/e801cd745080e052d01bacdc75dd118c to your computer and use it in GitHub Desktop.
Save yarigpopov/e801cd745080e052d01bacdc75dd118c to your computer and use it in GitHub Desktop.
import { Machine } from "xstate";
function noop() {}
const async = Machine(
{
initial: "idle",
context: {
trigger: noop,
onSuccess: noop,
onError: noop
},
states: {
idle: {
on: {
DO: "busy"
}
},
busy: {
invoke: {
id: "async",
src: (context) => context.trigger,
onDone: {
target: "success"
},
onError: {
target: "error"
}
}
},
success: {
entry: "handleSuccess",
on: {
DO: "busy"
}
},
error: {
entry: "handleError",
on: {
DO: "busy"
}
}
}
},
{
actions: {
handleSuccess(context, event) {
const { data } = event;
context.onSuccess(data);
},
handleError(context, event) {
const { data } = event;
context.onError(data);
}
}
}
);
export default async;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment