Skip to content

Commit 80c7d37

Browse files
committed
✨ feat: Added task persistency using localstorage and custom hook with reducer.
1 parent 34cdc12 commit 80c7d37

File tree

3 files changed

+26
-6
lines changed

3 files changed

+26
-6
lines changed

app/Components/TasksApp/TaskApp.tsx

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@
33
import { useEffect, useReducer } from "react";
44
import AddTask from "./AddTask";
55
import TaskList from "./TaskList";
6+
import useLocalStorageReducer from "@/app/_lib/customHooks/useLocalStorageWithReducer";
67

78
export default function TaskApp() {
8-
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
9+
//const [tasks, setTasks] = useLocalStorage("tasks", []);
10+
const [tasks, dispatch] = useLocalStorageReducer(tasksReducer, "tasks", initialTasks);
911

1012
useEffect(() => {
1113
const handleKeyDown = (event: KeyboardEvent) => {
@@ -56,10 +58,10 @@ export default function TaskApp() {
5658
);
5759
}
5860

59-
function tasksReducer(tasks: any, action: any) {
61+
function tasksReducer(tasks: Array<any>, action: any) {
6062
switch (action.type) {
6163
case "added": {
62-
return [
64+
const newTasks = [
6365
...tasks,
6466
{
6567
id: action.id,
@@ -68,11 +70,13 @@ function tasksReducer(tasks: any, action: any) {
6870
isNew: action.isNew,
6971
},
7072
];
73+
//setSavedTasks(newTasks);
74+
return newTasks;
7175
}
7276
case "changed": {
7377
return tasks.map((t: any) => {
7478
if (t.id === action.task.id) {
75-
return action.task;
79+
return {...action.task, isNew: false};
7680
} else {
7781
return t;
7882
}

app/Components/TasksApp/TaskList.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,6 @@ function Task({
5353
audio.play();
5454
};
5555

56-
console.log("Task", task);
57-
5856
const [isEditing, setIsEditing] = useState(task.isNew);
5957
let taskContent;
6058
if (isEditing) {
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { Reducer, ReducerWithoutAction, useEffect, useReducer } from "react";
2+
3+
export default function useLocalStorageReducer(
4+
reducer: Reducer<any, any>,
5+
key: string,
6+
initialState: Array<any>
7+
) {
8+
const [state, dispatch] = useReducer(reducer, initialState, () => {
9+
const persisted = localStorage.getItem(key);
10+
return persisted ? JSON.parse(persisted) : initialState;
11+
});
12+
13+
useEffect(() => {
14+
localStorage.setItem(key, JSON.stringify(state));
15+
}, [key, state]);
16+
17+
return [state, dispatch];
18+
}

0 commit comments

Comments
 (0)