Skip to content

Commit

Permalink
✨ feat: Added task persistency using localstorage and custom hook wit…
Browse files Browse the repository at this point in the history
…h reducer.
  • Loading branch information
bytevictor committed Mar 28, 2024
1 parent 34cdc12 commit 80c7d37
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
12 changes: 8 additions & 4 deletions app/Components/TasksApp/TaskApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -56,10 +58,10 @@ export default function TaskApp() {
);
}

function tasksReducer(tasks: any, action: any) {
function tasksReducer(tasks: Array<any>, action: any) {
switch (action.type) {
case "added": {
return [
const newTasks = [
...tasks,
{
id: action.id,
Expand All @@ -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;
}
Expand Down
2 changes: 0 additions & 2 deletions app/Components/TasksApp/TaskList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ function Task({
audio.play();
};

console.log("Task", task);

const [isEditing, setIsEditing] = useState(task.isNew);
let taskContent;
if (isEditing) {
Expand Down
18 changes: 18 additions & 0 deletions app/_lib/customHooks/useLocalStorageWithReducer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Reducer, ReducerWithoutAction, useEffect, useReducer } from "react";

export default function useLocalStorageReducer(
reducer: Reducer<any, any>,
key: string,
initialState: Array<any>
) {
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];
}

0 comments on commit 80c7d37

Please sign in to comment.