How to update state machine

273 views Asked by At

Is it possible to replace the currently initialized state machine in React?

For example, I initialize a state machine via Provider with a dummy configuration. Then, upon entering a specific page in the app, I update it via context.

Background of what I want to achieve: Consumer can either load the configuration globally or page-specific. Let's say for example that a required data for your config is unknown until you reach a specific portion of your page. So, only then you can properly create a state machine. Or, if consumer wants to keep the configuration per module/page. Bec doing this at the top level would mean, you have to collate all configurations which can get lengthy and hard to debug assuming you know the configuration in advance.

In provider

const dummyConfig =  {
  id: 'init',
  initial: 'init_state',
  states: {
    init_state: {
      on: {},
    },
  },
};
const initMachine = createMachine(dummyConfig);
const [stateMachine, setStateMachine] = useState(initMachine);

// stateMachine does not get updated with the new machine from the child component below
// passed via setMachine callback in the context
const [current, send, service] = useMachine(stateMachine);

const updateMachine = useCallback((machine: StateMachine) => {
   setStateMachine(machine);
}, []);

return (
    <MachineContext.Provider value={[current, send, service, updateMachine]}>
      {children}
    </StateMachineContext.Provider>
);

In child component somewhere in the app

const machine = createMachine(newConfig);

// Context hook
const { current, send, servicee, updateMachine } = useStateMachine();

// I can receive the new machine up in the provider (checked via console log),
// but it does not update the machine
// The value of current remains that from the first created machine
updateMachine(machine);
0

There are 0 answers