Advertisement
Guest User

Untitled

a guest
Feb 24th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. const XState = require('xstate')
  2.  
  3. const { Machine, interpret } = XState
  4. const { raise } = XState.actions
  5.  
  6. /*
  7. run from cli using:
  8. node xstate-onentry-timing-bug.js [sync|async|raise]
  9. */
  10.  
  11. let validate
  12.  
  13. switch (process.argv[2]) {
  14. case 'raise':
  15. validate = raise('ERROR')
  16. break
  17.  
  18. case 'async':
  19. validate = () => {
  20. setTimeout(() => service.send('ERROR'))
  21. }
  22. break
  23.  
  24. case 'sync':
  25. default:
  26. validate = () => {
  27. service.send('ERROR')
  28. }
  29. break
  30. }
  31.  
  32. console.log(
  33. 'Using `validate` action:\n',
  34. typeof validate === 'object' ? JSON.stringify(validate) : validate.toString(),
  35. '\n'
  36. )
  37.  
  38. const m = Machine(
  39. {
  40. id: 'form',
  41. initial: 'filling',
  42. states: {
  43. filling: {
  44. on: {
  45. SUBMIT: 'validating',
  46. },
  47. },
  48. validating: {
  49. onEntry: 'validate',
  50. on: {
  51. SUCCESS: 'ok',
  52. ERROR: 'filling',
  53. },
  54. },
  55. ok: {},
  56. },
  57. },
  58. {
  59. actions: {
  60. validate,
  61. },
  62. }
  63. )
  64.  
  65. const start = Date.now()
  66. const timestamp = () => `${Date.now() - start}ms`.padEnd(7)
  67.  
  68. const service = interpret(m)
  69. .onEvent(ev => {
  70. console.log(timestamp(), 'event:', ev)
  71. })
  72. .onTransition(state => {
  73. console.log(timestamp(), 'Transition to', state.value)
  74. })
  75. .start()
  76.  
  77. const delay = ms => new Promise(resolve => setTimeout(resolve, ms || 1000))
  78.  
  79. delay()
  80. .then(() => console.log(timestamp(), 'submitting...') || service.send('SUBMIT'))
  81. .then(delay)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement