Created
November 21, 2019 23:06
-
-
Save shanebdavis/8e3be17e4ad50b6fcb53dd5536202e29 to your computer and use it in GitHub Desktop.
The core of the TODO app using hooks-for-redux
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
import React, { useState } from "react"; | |
import ReactDOM from "react-dom"; | |
import { Provider, useRedux } from "hooks-for-redux"; | |
// redux/list.js | |
const getUniqueId = list => | |
list.length > 0 ? Math.max(...list.map(t => t.id)) + 1 : 1; | |
const [useList, { addItem, deleteItem }] = useRedux( | |
"list", | |
[ | |
{ id: 1, text: "clean the house" }, | |
{ id: 2, text: "buy milk" } | |
], | |
{ | |
addItem: (list, item) => [...list, { ...item, id: getUniqueId(list) }], | |
deleteItem: (list, item) => list.filter(todo => todo.id !== item.id) | |
} | |
); | |
// components/ToDoItem.js | |
const ToDoItem = ({ item }) => | |
<li> | |
{item.text} | |
| |
<button className="ToDoItem-Delete" onClick={() => deleteItem(item)}> | |
- | |
</button> | |
</li> | |
// components/ToDo.js | |
const ToDo = () => { | |
const list = useList(); | |
const [text, setText] = useState(""); | |
const createNewToDoItem = () => { | |
if (!text) return alert("Please enter a text!"); | |
addItem({ text }); | |
setText(""); | |
}; | |
return <div> | |
<h1>Todo with hooks-for-redux</h1> | |
<ul> | |
{list.map(item => ( | |
<ToDoItem key={item.id} item={item} /> | |
))} | |
</ul> | |
<input | |
type="text" | |
value={text} | |
onChange={e => setText(e.target.value)} | |
onKeyPress={e => e.key === "Enter" && createNewToDoItem()} | |
/> | |
| |
<button onClick={createNewToDoItem}>+</button> | |
</div> | |
}; | |
// index.js | |
ReactDOM.render( | |
<Provider><ToDo /></Provider>, | |
document.getElementById("root") | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment