reactjstypescriptnext.jsstate-machinexstate

Problem to check the current machine state using XState in React


im trying to check the Machine state from inside a function in a react component (state.value), but its never change the current state, it always prints the initial state, but if i put a onClick event in the component and call console.log(state.value), it works... Im doing something wrong?

const [state, send] = useMachine(knightMachine);

const loop = ()  => {
    console.log(state.value);
    
     setTimeout(loop, 10);
    
    }
    
    /// Always print the initial state.


    <div
    onClick={() => {
    console.log(state.value);
    }}
    ></div>
    
    /// It Prints the right value

Solution

  • This is likely due to a stale closure. You are always reading the closed-in value of state in the loop.

    Instead, you can read from service.getSnapshot():

    const [state, send, service] = useMachine(knightMachine);
    
    // ...
    
    console.log(service.getSnapshot().value); // up-to-date value
    
    // ...