Skip to content

Instantly share code, notes, and snippets.

@kimroen
Created August 12, 2020 14:37
Show Gist options
  • Save kimroen/6ce394496615df38337ee6fd6b55b99c to your computer and use it in GitHub Desktop.
Save kimroen/6ce394496615df38337ee6fd6b55b99c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const initialContext = {
file: 'NO VALUE',
success: 'NO VALUE',
direction: 1,
error: 'NO VALUE',
validationError: 'NO VALUE',
};
const UploadMachine = Machine({
id: 'upload',
context: initialContext,
initial: 'idle',
states: {
idle: {
entry: [
assign({
file: 'NO VALUE',
success: 'NO VALUE',
}),
],
on: {
VALIDATE: {
target: 'validating',
actions: [
assign({
direction: 1,
file: 'some file',
}),
],
},
},
},
validating: {
type: 'parallel',
states: {
runningChecks: {
type: 'parallel',
states: {
checkingFileType: {
initial: 'pending',
states: {
pending: {
invoke: {
src: 'onCheckingFileType',
onDone: 'done',
onError: {
target: 'done',
actions: [
send({
type: 'VALIDATION_ERROR',
payload: 'file type validation error',
}),
],
},
},
},
done: {
type: 'final',
},
},
},
checkingFileSize: {
initial: 'pending',
states: {
pending: {
invoke: {
src: 'onCheckingFileSize',
onDone: 'done',
onError: {
target: 'done',
actions: [
send({
type: 'VALIDATION_ERROR',
payload: 'file size validation error',
}),
],
},
},
},
done: {
type: 'final',
},
},
},
},
},
minimumWait: {
initial: 'pending',
states: {
pending: {
after: {
3000: 'success',
},
},
success: {
type: 'final',
},
},
},
},
on: {
VALIDATION_ERROR: {
actions: [
assign({
validationError: (_, event) => event.payload,
}),
],
},
},
onDone: [
{
// If there's a validation error, we set "error" and go to error state
target: 'error',
actions: [
assign({ direction: -1 }),
assign({ error: (context) => context.validationError }),
],
cond: (context) => context.validationError !== 'NO VALUE',
},
{ target: 'uploading', actions: [assign({ direction: 1 })] },
],
entry: [assign({ validationError: 'NO VALUE' })],
},
uploading: {
invoke: {
src: 'onUploading',
onDone: {
target: 'uploaded',
actions: [
assign({ direction: 1 }),
assign({
success: (_, event) => event.data,
}),
],
},
onError: {
target: 'error',
actions: [
assign({ direction: -1 }),
assign({
error: 'some error',
}),
],
},
},
},
uploaded: {
type: 'final',
},
error: {
exit: [assign({ error: 'NO VALUE' })],
on: {
RETRY: {
target: 'validating',
actions: assign({ direction: 1 }),
},
TRY_ANOTHER: {
target: 'idle',
actions: assign({ direction: 1 }),
},
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment