|
1 | 1 | # xstate-logger
|
| 2 | + |
| 3 | + <img src="./screenshot.png" alt="xstate-logger"/> |
| 4 | + |
2 | 5 | redux-logger but for XState
|
3 | 6 |
|
4 | 7 | Please feel free to open issues to improve this logger.
|
| 8 | + |
| 9 | +## Quick Start |
| 10 | + |
| 11 | +1. Install `xstate` and `xstate-logger`: |
| 12 | + |
| 13 | +```bash |
| 14 | +yarn add xstate xstate-logger |
| 15 | +``` |
| 16 | + |
| 17 | +2. Import the `xstateLogger` function: |
| 18 | + |
| 19 | +```ts |
| 20 | +import { createMachine, interpret } from 'xstate'; |
| 21 | +import { xstateLogger } from 'xstate-logger'; |
| 22 | + |
| 23 | +// Stateless machine definition |
| 24 | +// machine.transition(...) is a pure function used by the interpreter. |
| 25 | +const toggleMachine = createMachine({ |
| 26 | + id: 'toggle', |
| 27 | + initial: 'inactive', |
| 28 | + states: { |
| 29 | + inactive: { on: { TOGGLE: 'active' } }, |
| 30 | + active: { on: { TOGGLE: 'inactive' } } |
| 31 | + } |
| 32 | +}); |
| 33 | + |
| 34 | +// Machine instance with internal state |
| 35 | +const toggleService = interpret(toggleMachine) |
| 36 | + .onTransition((state) => xstateLogger(state)) |
| 37 | + .start(); |
| 38 | +// => 'event xstate.init' |
| 39 | + |
| 40 | +toggleService.send('TOGGLE'); |
| 41 | +// => 'event TOGGLE' |
| 42 | + |
| 43 | +toggleService.send('TOGGLE'); |
| 44 | +// => 'event TOGGLE' |
| 45 | +``` |
| 46 | + |
| 47 | +## Usage with @xstate/react |
| 48 | +1. Install `xstate`, `@xstate/react` and `xstate-logger`: |
| 49 | + |
| 50 | +```bash |
| 51 | +yarn add xstate @xstate/react xstate-logger |
| 52 | +``` |
| 53 | + |
| 54 | +2. Import the `xstateLogger` function: |
| 55 | + |
| 56 | +```ts |
| 57 | +import { createMachine } from 'xstate'; |
| 58 | +import { useMachine } from '@xstate/react'; |
| 59 | +import { xstateLogger } from 'xstate-logger'; |
| 60 | + |
| 61 | +const toggleMachine = createMachine({ |
| 62 | + id: 'toggle', |
| 63 | + initial: 'inactive', |
| 64 | + states: { |
| 65 | + inactive: { |
| 66 | + on: { TOGGLE: 'active' } |
| 67 | + }, |
| 68 | + active: { |
| 69 | + on: { TOGGLE: 'inactive' } |
| 70 | + } |
| 71 | + } |
| 72 | +}); |
| 73 | + |
| 74 | +export const Toggler = () => { |
| 75 | + const [state, send] = useMachine(toggleMachine); |
| 76 | + |
| 77 | + if (process.env.NODE_ENV !== 'production') { |
| 78 | + useEffect(() => { |
| 79 | + const subscription = service.subscribe(xstateLogger); |
| 80 | + return subscription.unsubscribe; |
| 81 | + }, [service]); |
| 82 | + } |
| 83 | + |
| 84 | + return ( |
| 85 | + <button onClick={() => send('TOGGLE')}> |
| 86 | + {state.value === 'inactive' |
| 87 | + ? 'Click to activate' |
| 88 | + : 'Active! Click to deactivate'} |
| 89 | + </button> |
| 90 | + ); |
| 91 | +}; |
| 92 | +``` |
0 commit comments