Last active
November 4, 2021 14:12
-
-
Save jacksteamdev/24a909623afa298a5457f682e2cd084b to your computer and use it in GitHub Desktop.
XState Debug Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const service = interpret(someMachine); | |
debugHelper(service, (state, ids, actors) => { | |
// debug here, this will run on all actors | |
console.log(state, ids); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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], | |
}); | |
}); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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], | |
}) | |
}) | |
}) | |
} |
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
I'm getting TS error on line 18-19 - you don't?