Skip to content

Instantly share code, notes, and snippets.

@cevr
Last active June 8, 2019 22:17
Show Gist options
  • Save cevr/a3706f346a284d202ac37ce007e6598c to your computer and use it in GitHub Desktop.
Save cevr/a3706f346a284d202ac37ce007e6598c to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from 'react';
import { useActions, useStore } from 'easy-peasy';
export default function App() {
return (
<div>
<h1 style={{ margin: 0 }}>Todo</h1>
<Todos />
<AddTodo />
</div>
);
}
function AddTodo() {
const [text, setText] = useState('');
const save = useActions(actions => actions.add);
const handleAddClick = () => {
save(text);
setText('');
};
const handleTextChange = e => setText(e.target.value);
return (
<div>
<input
value={text}
onChange={handleTextChange}
placeholder="What to do next"
/>
{text && <button onClick={handleAddClick}>Add</button>}
</div>
);
}
function Todos() {
const todos = useStore(state => state.todos);
const { toggle, del } = useActions(actions => ({
toggle: actions.toggle,
del: actions.delete,
}));
const todosList = Object.values(todos);
return todosList.map(todo => (
<Todo key={todo.id} todo={todo} toggle={toggle} del={del} />
));
}
function Todo({ todo: { id, text, done }, toggle, del }) {
return (
<div
onClick={() => toggle(id)}
style={{
cursor: 'pointer',
textDecoration: done ? 'line-through' : undefined,
}}
>
{text}
<button
onClick={e => {
e.stopPropagation();
del(id);
}}
style={{ marginLeft: 10 }}
>
Delete
</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment