Created
May 14, 2021 18:58
-
-
Save jaidetree/733171a2a1fa80d2d7feb40d3bb9f807 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const todosMachine = Machine({ | |
id: "todos", | |
context: { | |
todo: "", // new todo | |
todos: [], | |
filter: "all" | |
}, | |
initial: "loading", | |
states: { | |
loading: { | |
entry: assign({ | |
todos: (context) => { | |
// "Rehydrate" persisted todos | |
return context.todos.map((todo) => ({ | |
...todo, | |
ref: spawn(createTodoMachine(todo)) | |
})); | |
} | |
}), | |
always: "ready" | |
}, | |
ready: {} | |
}, | |
on: { | |
"NEWTODO.CHANGE": { | |
actions: assign({ | |
todo: (_, event) => event.value | |
}) | |
}, | |
"NEWTODO.COMMIT": { | |
actions: [ | |
assign({ | |
todo: "", // clear todo | |
todos: (context, event) => { | |
const newTodo = createTodo(event.value.trim()); | |
return context.todos.concat({ | |
...newTodo, | |
ref: spawn(createTodoMachine(newTodo)) | |
}); | |
} | |
}), | |
"persist" | |
], | |
cond: (_, event) => event.value.trim().length | |
}, | |
"TODO.COMMIT": { | |
actions: [ | |
assign({ | |
todos: (context, event) => | |
context.todos.map((todo) => { | |
return todo.id === event.todo.id | |
? { ...todo, ...event.todo, ref: todo.ref } | |
: todo; | |
}) | |
}), | |
"persist" | |
] | |
}, | |
"TODO.DELETE": { | |
actions: [ | |
assign({ | |
todos: (context, event) => | |
context.todos.filter((todo) => todo.id !== event.id) | |
}), | |
"persist" | |
] | |
}, | |
SHOW: { | |
actions: assign({ | |
filter: (_, event) => event.filter | |
}) | |
}, | |
"MARK.completed": { | |
actions: (context) => { | |
context.todos.forEach((todo) => todo.ref.send("SET_COMPLETED")); | |
} | |
}, | |
"MARK.active": { | |
actions: (context) => { | |
context.todos.forEach((todo) => todo.ref.send("SET_ACTIVE")); | |
} | |
}, | |
CLEAR_COMPLETED: { | |
actions: assign({ | |
todos: (context) => context.todos.filter((todo) => !todo.completed) | |
}) | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment