Skip to content

Instantly share code, notes, and snippets.

@Andarist

Andarist/machine.js

Created Jul 15, 2019
Embed
What would you like to do?
Generated by [XState Viz](https://xstate.js.org/viz)
// Available variables:
// Machine (machine factory function)
// assign (action)
// XState (all XState exports)
const fetchMachine = Machine({
id: 'fetch',
context: { attempts: 0 },
initial: 'idle',
states: {
idle: {
on: {
FETCH: [{
target: 'rejected',
cond: function canFetch() {
return false
},
}, {
target: 'pending',
cond: function canFetch() {
return true
},
}, {
target: 'pending',
cond: function canFetch() {
return true
},
}]
},
},
pending: {
entry: assign({
attempts: ctx => ctx.attempts + 1
}),
after: {
TIMEOUT: 'rejected'
},
on: {
RESOLVE: 'fulfilled',
REJECT: 'rejected'
}
},
fulfilled: {
initial: 'first',
states: {
first: {
on: {
NEXT: 'second'
}
},
second: {
on: {
NEXT: 'third'
}
},
third: {
type: 'final'
}
}
},
rejected: {
entry: assign({
ref: () => spawn(Machine({ initial: 'foo', states: {foo: {}}}))
}),
initial: 'can retry',
states: {
'can retry': {
on: {
'': {
target: 'failure',
cond: 'maxAttempts'
}
}
},
failure: {
on: {
RETRY: undefined,
},
type: 'final'
}
},
on: {
RETRY: 'pending'
}
}
}
}, {
guards: {
maxAttempts: ctx => ctx.attempts >= 5
},
delays: {
TIMEOUT: 2000
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment