Xstate: sendParent invoke event handler twice on parent machine

Created on 19 Mar 2020  路  5Comments  路  Source: davidkpiano/xstate

Description
sendParent invokes event handler twice on parent machine

Expected Result
Event handler on parent machine should only be invoked once.

Actual Result
Event handler on parent is invoked two times

Reproduction

The

sendParent(ctx => ({ type: "TODO.COMMIT", todo: ctx }))

in the todoMachine.js will invoke "TODO.COMMIT" two times on todosMachine.js
The problem can be seen by adding a console.log in the handler for "TODO.COMMIT" in todosMachine.js

Additional context

bug

Most helpful comment

This happens because of this:

  useEffect(() => {
    todoRef.execute(state, {
      focusInput() {
        inputRef.current && inputRef.current.select();
      }
    });
  }, [state, todoRef]);

state should not be used as a dependency of an effect - by doing this, actions of a particular state might get fired twice (once during regular execution and once in this effect).

All 5 comments

Just tested this; it's only being called once. Can you create a simple reproduction?

https://codesandbox.io/s/xstate-todomvc-6nlwe
Added a console.log in todosMachine.js (line: 70-72)
If I edit an existing todo and press Enter, there will be two console.logs from the todosMachine

This happens because of this:

  useEffect(() => {
    todoRef.execute(state, {
      focusInput() {
        inputRef.current && inputRef.current.select();
      }
    });
  }, [state, todoRef]);

state should not be used as a dependency of an effect - by doing this, actions of a particular state might get fired twice (once during regular execution and once in this effect).

Yeah, we'll have to edit the docs for this one, and introduce the useAction hook to make this safer.

This would be better done (right now) as:

useEffect(() => {
  state.actions.forEach(action => {
    if (action.type === 'focusInput') {
      inputRef.current && inputRef.current.select();
    }
  });
}, [state]);

Thank you for the quick reply. That cleared up my confusion.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bradwoods picture bradwoods  路  3Comments

doup picture doup  路  3Comments

greggman picture greggman  路  3Comments

hnordt picture hnordt  路  3Comments

ifokeev picture ifokeev  路  3Comments