From 3f4b015a850105ac8a1f0e0da23033e3c888246e Mon Sep 17 00:00:00 2001 From: Joshua Seigler Date: Sun, 9 Oct 2022 23:23:30 -0400 Subject: [PATCH] functional useState demo --- src/strategies/useState.tsx | 91 +++++++++++++++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 3 deletions(-) diff --git a/src/strategies/useState.tsx b/src/strategies/useState.tsx index bfa4504..51b2e04 100644 --- a/src/strategies/useState.tsx +++ b/src/strategies/useState.tsx @@ -1,26 +1,63 @@ import React, { useState } from 'react' +import localforage from 'localforage' type Todo = { id: string text: string - status: 'incomplete' | 'complete' | 'hidden' + status: 'incomplete' | 'complete' } export function UseState() { + const [isLoading, setLoading] = useState(true) const [todos, setTodos] = 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() { const newTodo = { id: crypto.randomUUID(), text: newTodoText, 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 ( -
+
+
{ e.preventDefault() @@ -38,3 +75,51 @@ export function UseState() {
) } + +function TodoList({ + todos, + todoSetter +}: { + todos: Todo[] + todoSetter: (id: string, newValue?: Todo) => void +}) { + return ( + <> + {todos.map((todo) => ( + + ))} + + ) +} + +function TodoItem({ + todo, + todoSetter +}: { + todo: Todo + todoSetter: (id: string, newValue?: Todo) => void +}) { + return ( + + ) +}