Created
January 26, 2019 15:57
-
-
Save ryanflorence/1390b82d3397b2e926929d3e1d50595b to your computer and use it in GitHub Desktop.
This file contains 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 { useState, useMemo, useEffect } from "react"; | |
import { interpret } from "xstate/lib/interpreter"; | |
export default function useMachine(machine, { log = false } = {}) { | |
const [current, setCurrent] = useState(machine.initialState); | |
const service = useMemo(() => interpret(machine), []); | |
useEffect(() => { | |
service.onTransition(setCurrent).start(); | |
return () => service.stop(); | |
}, []); | |
useEffect( | |
() => { | |
if (log) { | |
console.group(current.value); | |
console.log("event", current.event); | |
console.log("state:", current.value); | |
console.log("next: ", current.nextEvents.join(", ")); | |
console.log("context", current.context); | |
console.groupEnd(current.value); | |
} | |
}, | |
[log, current.value] | |
); | |
return [current, service.send]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment