Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. // Available variables:
  2. // - Machine
  3. // - interpret
  4. // - assign
  5. // - send
  6. // - sendParent
  7. // - spawn
  8. // - raise
  9. // - actions
  10. // - XState (all XState exports)
  11.  
  12. const config = {
  13. id: 'search',
  14. initial: 'idle',
  15. context: {
  16. valid: true,
  17. name: 'Mikael Karon'
  18. },
  19. states: {
  20. idle: {
  21. type: 'parallel',
  22. states: {
  23. input: {
  24. initial: 'invalid',
  25. states: {
  26. invalid: {
  27. on: {
  28. '': { target: 'valid', cond: 'valid' }
  29. }
  30. },
  31. valid: { on: { SUBMIT: '#search.pending' } }
  32. },
  33. on: { INPUT: { target: 'input', actions: 'input' } }
  34. },
  35. results: {
  36. initial: 'empty',
  37. states: {
  38. empty: {
  39. on: {
  40. '': { target: 'found', cond: 'found' }
  41. }
  42. },
  43. found: {
  44. on: { SELECT: '#search.done' }
  45. }
  46. }
  47. }
  48. }
  49. },
  50. pending: {
  51. entry: 'pending',
  52. invoke: {
  53. src: 'submit',
  54. onDone: { target: 'idle', actions: 'success' },
  55. onError: { target: 'idle', actions: 'error' }
  56. },
  57. after: { TIMEOUT: { target: 'idle', actions: 'timeout' } }
  58. },
  59. done: {
  60. type: 'final'
  61. }
  62. }
  63. };
  64.  
  65. const options = {
  66. actions: {
  67. input: assign((context, event) => ({
  68. ...context,
  69. ...event
  70. })),
  71. pending: assign({ error: undefined }),
  72. success: assign({
  73. results: (_context, event) => event.data
  74. }),
  75. error: assign({
  76. error: (_context, event) => event.data.message
  77. }),
  78. timeout: assign({ error: "Timeout: No response from backend" })
  79. },
  80. guards: {
  81. valid: context => context.valid,
  82. found: context => context.results
  83. },
  84. services: {
  85. submit: ({ name }) => Promise.resolve([{ name }])
  86. },
  87. delays: {
  88. TIMEOUT: 2000
  89. }
  90. };
  91.  
  92. const machine = Machine(config, options);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement