Skip to content

Instantly share code, notes, and snippets.

@dsadhanala
Last active April 17, 2020 08:57
Show Gist options
  • Save dsadhanala/eaa257488c80985aa8232506914d39b7 to your computer and use it in GitHub Desktop.
Save dsadhanala/eaa257488c80985aa8232506914d39b7 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const projectNameMachine = Machine(
{
id: 'project-name',
strict: true,
initial: 'editing',
states: {
editing: {
on: {
PROJECT_NAME_SAVING: {
cond: 'validProjectName',
actions: [
sendParent(
(
_context,
{ projectName }
) => ({
type: 'HEADER_SAVING',
projectName: projectName,
})
),
],
},
PROJECT_NAME_CANCEL: 'cancelled',
},
},
cancelled: {
on: { PROJECT_NAME_EDIT: 'editing' },
},
},
},
{
guards: {
validProjectName: (_context, { projectName }) => !!projectName,
},
}
);
const updateMessage = (message) => assign({ message: (_, _e) => message });
const forwardTo = (id) => send((_, e) => e, { to: id });
const headerActorsMachine = Machine(
{
id: 'header',
strict: true,
initial: 'ready',
context: {
downloadMenu: undefined,
shareMenu: undefined,
logo: undefined,
projectName: '',
message: undefined,
projectNameMachineRef: null,
},
states: {
ready: {
entry: assign({
projectNameMachineRef: (_context) => spawn(projectNameMachine, 'projectName')
}),
on: {
PROJECT_NAME_SAVING: {
actions: send({type:'PROJECT_NAME_SAVING', projectName: "some name"}, {to: 'projectName'})
}
}
},
saving: {
entry: ['updateLabel', updateMessage('Saving...')],
invoke: {
id: 'saveProject',
src: 'saveService',
onDone: {
target: 'saved',
actions: updateMessage('Saved'),
},
onError: {
target: 'failed',
actions: updateMessage('Failed to save!'),
},
},
},
saved: {},
failed: {},
},
on: {
HEADER_SAVING: '.saving',
HEADER_SAVED: '.saved',
HEADER_SAVE_FAILED: '.failed',
},
},
{
actions: {
updateLabel: assign({
projectName: (_, { projectName }) => projectName,
}),
},
services: {
saveService: () => {
// this is a fetch request which saves project
return new Promise((resolve, _reject) => {
setTimeout(resolve, 2000);
});
},
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment