0

I need to be able to access my state machine outside of a React component in a form session that is handled by a 3rd party. Here is the configuration I have and since I'm new to xstate I wanted to see if this was a proper solution:

// machine.js
const machine = createMachine({
  id: 'machine',
    // the initial context (extended state) of the statechart
    context: {
      amount: 0
    },
  }
})

const service = interpret(machine)

export default service

// formSession.js
import service from './machine'

function formSession() {
  const promiseFormInput = (): Promise<AnyType> => {
    return new Promise(resolve => {
      service.onTransition(state => {
        // this watches state
        console.log(state.context)

        // check if state context matches, not sure if this is right
        if(state.context.amount === 1) {
          console.log('1')
        }
      })
    }
  }
}

// App.jsx
import FormUI from './FormUi'
import service from './machine'

const App = () => {
  service.start()

  return <FormUi />
}

// FormUI.jsx
import service from './machine'

const FormUI = () => {
  const handleOnClick = () => {
    service.send({ type: 'FILL' })
  }
}
Jamie
  • 1,909
  • 3
  • 22
  • 47

0 Answers0