Xstate: useMachine is not working in custom hook

Created on 2 Jul 2020  路  4Comments  路  Source: davidkpiano/xstate

invalid question

Most helpful comment

  1. you are using your custom hook in the wrong way - you shouldn't use them within your return value, all of them should be statements near the top of your component declaration. In this particular situation, it would work, but it is not advised to do this in React. Also - hooks shouldn't usually return React elements.
  2. each useMachine starts a new machine. So in your example, you actually have 2 separate live toggle machines but you only send events to one of them. That's why the second one's state doesn't get updated and it displays 0 all the time.

All 4 comments

  1. you are using your custom hook in the wrong way - you shouldn't use them within your return value, all of them should be statements near the top of your component declaration. In this particular situation, it would work, but it is not advised to do this in React. Also - hooks shouldn't usually return React elements.
  2. each useMachine starts a new machine. So in your example, you actually have 2 separate live toggle machines but you only send events to one of them. That's why the second one's state doesn't get updated and it displays 0 all the time.

Thanks for your answer! @Andarist

  1. If it is wrong way, how can I extract very complex/verbose logic made by useMachine? Is it impossible?
  2. Great answer! I got it, this is very obvious explanation. 馃槃

If it is wrong way, how can I extract very complex/verbose logic made by useMachine? Is it impossible?

You would have to describe what exact problem do you have, I'm not sure what exactly is complex/verbose in your eyes so I can't answer this without learning more about your perspective.

I will close this as invalid - @baeharam Feel free to create a discussion if you want to talk about your use-case further.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bradwoods picture bradwoods  路  3Comments

dakom picture dakom  路  3Comments

3plusalpha picture 3plusalpha  路  3Comments

laurentpierson picture laurentpierson  路  3Comments

rodinhart picture rodinhart  路  3Comments