Skip to content

Instantly share code, notes, and snippets.

@barbados-clemens
Last active February 9, 2020 04:46
Show Gist options
  • Save barbados-clemens/e65afa5c88dcc41657771b85e4142da6 to your computer and use it in GitHub Desktop.
Save barbados-clemens/e65afa5c88dcc41657771b85e4142da6 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// https://xstate.js.org/viz/?gist=e65afa5c88dcc41657771b85e4142da6
const saveSelection = assign({
available: (ctx, event) => {
console.log('available', ctx.available);
// do some logic in here to verify selection
ctx.available.splice(0, 1);
return ctx.available;
},
selected: (ctx, event) => {
console.log('selected', ...ctx.selected, ctx.available[0]);
return [...ctx.selected, ctx.available[0]];
},
elapsed: () => 0
});
const draftMachine = Machine({
id: 'draft',
initial: 'waiting',
context: {
retries: 0,
elapsed: 0,
interval: 1,
duration: 3,
round: 0,
available: [
'name 1',
'name 2',
'name 3',
'name 4'
],
selected: [],
},
states: {
waiting: {
// wait for other people to draft
on: {
// selection made by other users
START: 'selecting'
}
},
selecting: {
invoke: {
src: context => cb => {
const interval = setInterval(() => {
cb('TICK');
}, 1000 * context.interval);
return () => {
clearInterval(interval);
};
},
},
on: {
'': {
target: 'saving',
cond: context => {
return context.elapsed >= context.duration;
}
},
// start timer for 5 minutes to select
// if selection or timer use send save event with payload
SAVE: {
target: 'saving',
actions: assign({
elapsed: ctx => ctx.duration
})
},
TICK: {
actions: assign({
elapsed: context => +(context.elapsed + context.interval).toFixed(2)
}),
},
}
},
saving: {
on: {
RESOLVE: {
target: 'success',
actions: saveSelection
},
REJECT: 'failure'
}
},
success: {
on: {
'': {
target: 'done',
cond: ctx => ctx.available.length === 0
}
},
after: {
5000: 'waiting'
// show a success message
}
},
// firebase will auto handle this
failure: {
on: {
RETRY: {
target: 'saving',
actions: assign({
retries: (context, event) => context.retries + 1
})
}
}
},
done: {
type: 'final'
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment