functional useState demo

This commit is contained in:
Joshua Seigler 2022-10-09 23:23:30 -04:00
parent 11d3fb8aaf
commit 3f4b015a85

View file

@ -1,26 +1,63 @@
import React, { useState } from 'react' import React, { useState } from 'react'
import localforage from 'localforage'
type Todo = { type Todo = {
id: string id: string
text: string text: string
status: 'incomplete' | 'complete' | 'hidden' status: 'incomplete' | 'complete'
} }
export function UseState() { export function UseState() {
const [isLoading, setLoading] = useState(true)
const [todos, setTodos] = useState<Todo[]>([]) const [todos, setTodos] = useState<Todo[]>([])
const [newTodoText, setNewTodoText] = useState('') const [newTodoText, setNewTodoText] = useState('')
localforage.getItem('react-state-management/todos', (_err, value) => {
if (value) {
setTodos(value as Todo[]) // validation first would be better
}
setLoading(false)
})
function updateTodos(newTodos: Todo[]) {
// alternative to tricky useEffect
setLoading(true)
setTodos(newTodos)
localforage.setItem('react-state-management/todos', newTodos).then(() => {
setLoading(false)
})
}
function addTodo() { function addTodo() {
const newTodo = { const newTodo = {
id: crypto.randomUUID(), id: crypto.randomUUID(),
text: newTodoText, text: newTodoText,
status: 'incomplete' as const status: 'incomplete' as const
} }
setTodos((t) => [...t, newTodo]) const newTodos = [...todos, newTodo]
setNewTodoText('')
updateTodos(newTodos)
}
function todoSetter(id: string, newValue?: Todo) {
updateTodos(
todos.reduce((acc, cur) => {
if (cur.id === id) {
if (newValue === undefined) {
return acc
} else {
return [...acc, newValue]
}
} else {
return [...acc, cur]
}
}, [] as Todo[])
)
} }
return ( return (
<main> <main style={isLoading ? { pointerEvents: 'none', cursor: 'wait' } : {}}>
<TodoList todos={todos} todoSetter={todoSetter} />
<form <form
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault() e.preventDefault()
@ -38,3 +75,51 @@ export function UseState() {
</main> </main>
) )
} }
function TodoList({
todos,
todoSetter
}: {
todos: Todo[]
todoSetter: (id: string, newValue?: Todo) => void
}) {
return (
<>
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} todoSetter={todoSetter} />
))}
</>
)
}
function TodoItem({
todo,
todoSetter
}: {
todo: Todo
todoSetter: (id: string, newValue?: Todo) => void
}) {
return (
<label
style={
todo.status === 'complete' ? { textDecoration: 'line-through' } : {}
}>
<a
style={{ float: 'right' }}
onClick={() => todoSetter(todo.id, undefined)}>
x
</a>
<input
type="checkbox"
onChange={(e) => {
todoSetter(todo.id, {
...todo,
status: e.target.checked ? 'complete' : 'incomplete'
})
}}
checked={todo.status === 'complete'}
/>{' '}
{todo.text}
</label>
)
}