Skip to content

Instantly share code, notes, and snippets.

@zerobias
Created June 16, 2019 21:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerobias/ad2628c2d0556c7162544755aa98a6af to your computer and use it in GitHub Desktop.
Save zerobias/ad2628c2d0556c7162544755aa98a6af to your computer and use it in GitHub Desktop.
todolist for effector-react with hooks

TODO list for effector-react with hooks

try it

import React from 'react'
import ReactDOM from 'react-dom'
import {createEvent, createStore, createApi, sample, combine} from 'effector'
import {useStore} from 'effector-react'
const inputStore = createStore('')
const todos = createStore([])
const visibilityFilter = createStore(todos => todos)
const submit = createEvent('sumbit form')
const onChange = createEvent('on change input')
const toggleTodo = createEvent('toggle todo')
const addTodo = sample(inputStore, submit).filter({
fn: input => input.length > 0,
})
inputStore
.on(onChange, (state, e) => e.currentTarget.value)
.reset(addTodo)
todos
.on(addTodo, (todos, text) => [...todos, {
text,
done: false,
id: todos.length,
}])
.on(toggleTodo, (todos, todoId) => todos.map(
todo => todo.id === todoId ? toggle(todo) : todo
))
const show = createApi(visibilityFilter, {
all: () => (todos => todos),
completed: () => (todos => todos.filter(({done}) => done)),
uncompleted: () => (todos => todos.filter(({done}) => !done)),
})
const visibleTodos = combine(
todos,
visibilityFilter,
(todos, filter) => filter(todos)
)
submit.watch(e => e.preventDefault())
const Input = () => (
<input
type="text"
value={useStore(inputStore)}
onChange={onChange}
/>
)
const List = () => (
<ul>
{useStore(visibleTodos).map(todo => (
<li key={todo.id} onClick={() => toggleTodo(todo.id)}>
{todo.text} - {todo.done ? "completed" : "uncompleted"}
</li>
))}
</ul>
)
const TodosPage = () => (
<div>
<form onSubmit={submit}>
<Input />
</form>
<List/>
<button onClick={show.all}>All</button>
<button onClick={show.completed}>Completed</button>
<button onClick={show.uncompleted}>Uncompleted</button>
</div>
)
const root = document.createElement('div')
document.body.appendChild(root)
ReactDOM.render(<TodosPage/>, root)
function toggle({text, done, id}) {
return {
text,
done: !done,
id,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment