diff --git a/app/Components/TasksApp/TaskApp.tsx b/app/Components/TasksApp/TaskApp.tsx index b61852c..ea7d69f 100644 --- a/app/Components/TasksApp/TaskApp.tsx +++ b/app/Components/TasksApp/TaskApp.tsx @@ -3,9 +3,11 @@ import { useEffect, useReducer } from "react"; import AddTask from "./AddTask"; import TaskList from "./TaskList"; +import useLocalStorageReducer from "@/app/_lib/customHooks/useLocalStorageWithReducer"; export default function TaskApp() { - const [tasks, dispatch] = useReducer(tasksReducer, initialTasks); + //const [tasks, setTasks] = useLocalStorage("tasks", []); + const [tasks, dispatch] = useLocalStorageReducer(tasksReducer, "tasks", initialTasks); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { @@ -56,10 +58,10 @@ export default function TaskApp() { ); } -function tasksReducer(tasks: any, action: any) { +function tasksReducer(tasks: Array, action: any) { switch (action.type) { case "added": { - return [ + const newTasks = [ ...tasks, { id: action.id, @@ -68,11 +70,13 @@ function tasksReducer(tasks: any, action: any) { isNew: action.isNew, }, ]; + //setSavedTasks(newTasks); + return newTasks; } case "changed": { return tasks.map((t: any) => { if (t.id === action.task.id) { - return action.task; + return {...action.task, isNew: false}; } else { return t; } diff --git a/app/Components/TasksApp/TaskList.tsx b/app/Components/TasksApp/TaskList.tsx index 29b104a..f8e7d13 100644 --- a/app/Components/TasksApp/TaskList.tsx +++ b/app/Components/TasksApp/TaskList.tsx @@ -53,8 +53,6 @@ function Task({ audio.play(); }; - console.log("Task", task); - const [isEditing, setIsEditing] = useState(task.isNew); let taskContent; if (isEditing) { diff --git a/app/_lib/customHooks/useLocalStorageWithReducer.tsx b/app/_lib/customHooks/useLocalStorageWithReducer.tsx new file mode 100644 index 0000000..67b7f9a --- /dev/null +++ b/app/_lib/customHooks/useLocalStorageWithReducer.tsx @@ -0,0 +1,18 @@ +import { Reducer, ReducerWithoutAction, useEffect, useReducer } from "react"; + +export default function useLocalStorageReducer( + reducer: Reducer, + key: string, + initialState: Array +) { + const [state, dispatch] = useReducer(reducer, initialState, () => { + const persisted = localStorage.getItem(key); + return persisted ? JSON.parse(persisted) : initialState; + }); + + useEffect(() => { + localStorage.setItem(key, JSON.stringify(state)); + }, [key, state]); + + return [state, dispatch]; +}