Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Available variables:
- // - Machine
- // - interpret
- // - assign
- // - send
- // - sendParent
- // - spawn
- // - raise
- // - actions
- // - XState (all XState exports)
- const config = {
- id: 'search',
- initial: 'idle',
- context: {
- valid: true,
- name: 'Mikael Karon'
- },
- states: {
- idle: {
- type: 'parallel',
- states: {
- input: {
- initial: 'invalid',
- states: {
- invalid: {
- on: {
- '': { target: 'valid', cond: 'valid' }
- }
- },
- valid: { on: { SUBMIT: '#search.pending' } }
- },
- on: { INPUT: { target: 'input', actions: 'input' } }
- },
- results: {
- initial: 'empty',
- states: {
- empty: {
- on: {
- '': { target: 'found', cond: 'found' }
- }
- },
- found: {
- on: { SELECT: '#search.done' }
- }
- }
- }
- }
- },
- pending: {
- entry: 'pending',
- invoke: {
- src: 'submit',
- onDone: { target: 'idle', actions: 'success' },
- onError: { target: 'idle', actions: 'error' }
- },
- after: { TIMEOUT: { target: 'idle', actions: 'timeout' } }
- },
- done: {
- type: 'final'
- }
- }
- };
- const options = {
- actions: {
- input: assign((context, event) => ({
- ...context,
- ...event
- })),
- pending: assign({ error: undefined }),
- success: assign({
- results: (_context, event) => event.data
- }),
- error: assign({
- error: (_context, event) => event.data.message
- }),
- timeout: assign({ error: "Timeout: No response from backend" })
- },
- guards: {
- valid: context => context.valid,
- found: context => context.results
- },
- services: {
- submit: ({ name }) => Promise.resolve([{ name }])
- },
- delays: {
- TIMEOUT: 2000
- }
- };
- const machine = Machine(config, options);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement