Skip to content

codingedgar/xstate-logger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

xstate-logger

xstate-logger

redux-logger but for XState

Please feel free to open issues to improve this logger.

Quick Start

  1. Install xstate and xstate-logger:
yarn add xstate xstate-logger
  1. Import the xstateLogger function:
import { createMachine, interpret } from 'xstate';
import { xstateLogger } from 'xstate-logger';

// Stateless machine definition
// machine.transition(...) is a pure function used by the interpreter.
const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: { on: { TOGGLE: 'active' } },
    active: { on: { TOGGLE: 'inactive' } }
  }
});

// Machine instance with internal state
const toggleService = interpret(toggleMachine)
  .onTransition((state) => xstateLogger(state))
  .start();
// => 'event xstate.init'

toggleService.send('TOGGLE');
// => 'event TOGGLE'

toggleService.send('TOGGLE');
// => 'event TOGGLE'

Usage with @xstate/react

  1. Install xstate, @xstate/react and xstate-logger:
yarn add xstate @xstate/react xstate-logger
  1. Import the xstateLogger function:
import { createMachine } from 'xstate';
import { useMachine } from '@xstate/react';
import { xstateLogger } from 'xstate-logger';

const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: { TOGGLE: 'active' }
    },
    active: {
      on: { TOGGLE: 'inactive' }
    }
  }
});

export const Toggler = () => {
  const [state, send] = useMachine(toggleMachine);

  if (process.env.NODE_ENV !== 'production') {
    useEffect(() => {
      const subscription = service.subscribe(xstateLogger);
      return subscription.unsubscribe;
    }, [service]);
  }

  return (
    <button onClick={() => send('TOGGLE')}>
      {state.value === 'inactive'
        ? 'Click to activate'
        : 'Active! Click to deactivate'}
    </button>
  );
};

About

redux-logger but for XState

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published