xstate with context provider code example

Example: xstate with context provider

import React, { useContext } from 'react'
import ReactDOM from 'react-dom'
import { MachineConfig } from 'xstate'
import { assign } from 'xstate/lib/actions'
import { useMachine, TCreateContext } from './use-machine'

type TContext = {
  counter: number
}

type TSchema = {
  states: {
    Off: {},
    On: {}
  }
}

type TEvent = {
  type: 'Tick'
}

const incAction = assign(context => ({ counter: context.counter + 1 }))

const machineConfig: MachineConfig = {
  initial: 'Off',
  context: {
    counter: 0
  },
  states: {
    Off: { on: { Tick: { target: 'On', actions: [incAction, 'sideEffect'] } } },
    On: { on: { Tick: { target: 'Off', actions: incAction } } }
  }
}

type TMachine = TCreateContext

const MachineContext = React.createContext({} as TMachine)

function App() {
  const machine = useMachine(machineConfig, {
    actions: {
      sideEffect: () => console.log('sideEffect')
    }
  })

  function sendTick() {
    machine.send('Tick')
  }

  return (
    
{machine.state.matches('Off') ? 'Off' : 'On'} Pressed: {machine.context.counter} times
) } function Child() { const machine = useContext(MachineContext) return (
Child state: {machine.state.matches('Off') ? 'Off' : 'On'}
Child count: {machine.context.counter}
) } function OtherChild() { const machine = useContext(MachineContext) function sendTick() { machine.send('Tick') } return (
OtherChild state: {machine.state.matches('Off') ? 'Off' : 'On'}
OtherChild count: {machine.context.counter}
) } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement)

Tags:

Misc Example