Created
December 18, 2020 09:51
-
-
Save zaydek/5626a5785043dcfa45c67164f9b00430 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { useEffect, useRef } from "react" | |
import useMethods from "use-methods" | |
const app = { | |
initialState: { | |
todo: "", | |
todos: [], | |
}, | |
reducer: state => ({ | |
setTodo(newTodo) { | |
state.todo = newTodo | |
}, | |
addTodo() { | |
if (!state.todo) { | |
// No-op | |
return | |
} | |
state.todos.unshift({ | |
key: Math.random(), | |
text: state.todo, | |
}) | |
state.todo = "" | |
}, | |
setTodoByKey(key, newTodo) { | |
const found = state.todos.find(each => each.key === key) | |
if (found === null) { | |
// No-op | |
return | |
} | |
found.text = newTodo | |
}, | |
removeTodoByKey(key) { | |
const x = state.todos.findIndex(each => each.key === key) | |
if (x === -1) { | |
// No-op | |
return | |
} | |
state.todos.splice(x, 1) | |
}, | |
}), | |
} | |
export default function TodoApp() { | |
const todoRef = useRef() | |
const [state, methods] = useMethods(app.reducer, {}, () => { | |
const raw = localStorage.getItem("todoAppState") | |
if (!raw) { | |
localStorage.removeItem("todoAppState") | |
return app.initialState | |
} | |
return JSON.parse(raw) | |
}) | |
useEffect(() => { | |
localStorage.setItem("todoAppState", JSON.stringify(state)) | |
// const id = setTimeout(() => { | |
// console.log("Hello, world!") | |
// }, 2e3) | |
// return () => { | |
// clearTimeout(id) | |
// } | |
}, [state]) | |
async function handleSubmit(e) { | |
e.preventDefault() | |
methods.addTodo() | |
todoRef.current.focus() | |
} | |
return ( | |
<form onSubmit={handleSubmit}> | |
<div> | |
<input ref={todoRef} type="text" value={state.todo} onChange={e => methods.setTodo(e.target.value)} /> | |
<button type="submit">+</button> | |
</div> | |
{state.todos.map(todo => ( | |
<div key={todo.key}> | |
<input type="text" value={todo.text} onChange={e => methods.setTodoByKey(todo.key, e.target.value)} /> | |
<button onClick={e => methods.removeTodoByKey(todo.key)}>-</button> | |
</div> | |
))} | |
<pre>{JSON.stringify(state, null, 2)}</pre> | |
</form> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment