Skip to content

Instantly share code, notes, and snippets.

@jacksteamdev
Last active November 4, 2021 14:12
Show Gist options
  • Save jacksteamdev/24a909623afa298a5457f682e2cd084b to your computer and use it in GitHub Desktop.
Save jacksteamdev/24a909623afa298a5457f682e2cd084b to your computer and use it in GitHub Desktop.
XState Debug Helper
const service = interpret(someMachine);
debugHelper(service, (state, ids, actors) => {
// debug here, this will run on all actors
console.log(state, ids);
});
import { interpret } from 'xstate';
export function debugHelper(service, subscriber, { actors, ids: pids } = {
actors: new Map(),
ids: [],
}) {
const ids = pids.length > 0 ? pids : [service.id];
actors.set(service, ids);
service.subscribe((state) => {
subscriber(state, ids, actors);
if (state === null || state === void 0 ? void 0 : state.children)
Object.entries(state.children).forEach(([id, ref]) => {
if (actors.has(ref))
return;
debugHelper(ref, subscriber, {
actors,
ids: [...ids, id],
});
});
});
}
import { EventObject, Interpreter, State, ActorRef, interpret } from 'xstate';
export function debugHelper<
TContext,
TEvent extends EventObject,
>(
service:
| Interpreter<TContext, any, TEvent>
| ActorRef<any, any>,
subscriber: (
state: State<any, EventObject>,
ids: string[],
actors: Map<any, string[]>,
) => void,
{ actors, ids: pids } = {
actors: new Map<any, string[]>(),
ids: [] as string[],
},
): void {
const ids = pids.length > 0 ? pids : [service.id]
actors.set(service, ids)
service.subscribe((state) => {
subscriber(state, ids, actors)
if (state?.children)
Object.entries(
state.children as Record<
string,
ActorRef<EventObject, unknown>
>,
).forEach(([id, ref]) => {
if (actors.has(ref)) return
debugHelper(ref, subscriber, {
actors,
ids: [...ids, id],
})
})
})
}
@NixBiks
Copy link

NixBiks commented Oct 6, 2021

I'm getting TS error on line 18-19 - you don't?

@jacksteamdev
Copy link
Author

jacksteamdev commented Nov 4, 2021

Looks like I forgot to include the format helper function... I'll just remove the log file printer, it's easy to throw together.

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