Skip to content

Instantly share code, notes, and snippets.

@Kelin2025
Last active September 14, 2022 05:45
Show Gist options
  • Save Kelin2025/898963ddcdebc4cc797b60ff01d62f75 to your computer and use it in GitHub Desktop.
Save Kelin2025/898963ddcdebc4cc797b60ff01d62f75 to your computer and use it in GitHub Desktop.
import { createStore, createEvent } from 'effector'
const inputChanged = createEvent('Input changed')
const todoAdded = createEvent('Todo added')
const todoRemoved = createEvent('Todo removed')
const todoToggled = createEvent('Todo toggled')
// We added one more event here
const submitPressed = createEvent('Submit pressed')
const $todo = createStore('')
const $todos = createStore([])
const $todosCount = $todos.map(todos => todos.length)
const $completedTodos = $todos.map(todos => todos.filter(todo => todo.completed))
$todo
.on(inputChanged, (state, value) => value)
.on(todoAdded, () => '')
$todos
.on(todoAdded, (todos, text) => [...todos, ({ text, completed: false })])
.on(todoRemoved, (todos, idx) => todos.filter((_, curIdx) => curIdx !== idx))
.on(todoToggled, (todos, idx) => {
return todos.map((todo, curIdx) => {
if (curIdx === idx) {
return { ...todo, completed: !todo.completed }
} else {
return todo
}
})
})
// Use event.watch(payload => ...) to do something on event call
// Also works for stores: store.watch(state => ...)
// Here we call "todoAdded" when form is submit
submitPressed.watch(evt => {
evt.preventDefault()
// Stores have .getState() method to get current state
todoAdded($todo.getState())
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment