refactor(logic): extract task management into useTasks custom hook

This commit is contained in:
2026-04-27 14:37:07 +02:00
parent 529c3f55b9
commit e102c83344
2 changed files with 45 additions and 37 deletions
+5 -37
View File
@@ -1,43 +1,11 @@
import { useEffect, useState } from "react"
import type { Task } from "./types/task";
import { useState } from "react"
import { TaskItem } from "./components/TaskItem";
import { useTasks } from "./hooks/useTasks";
function App() {
const [tasks, setTasks] = useState<Task[]>(() => {
const savedTasks = localStorage.getItem('tasks');
return savedTasks ? JSON.parse(savedTasks) : []
});
const [inputValue, setInputValue] = useState<string>('');
useEffect(() => {
localStorage.setItem('tasks', JSON.stringify(tasks));
}, [tasks]);
const addTask = () => {
if (inputValue.trim() === '') return;
const newTask: Task = {
id: Date.now(),
title: inputValue,
completed: false,
createdAt: new Date().toISOString()
};
setTasks([...tasks, newTask]);
setInputValue('');
};
const deleteTask = (id: number) => {
setTasks(tasks.filter(task => task.id !== id));
}
const toggleTask = (id: number) => {
setTasks(tasks.map(task =>
task.id === id ? { ...task, completed: !task.completed} : task
));
};
const { tasks, addTask, deleteTask, toggleTask } = useTasks();
return (
<div className="container">
@@ -49,7 +17,7 @@ function App() {
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button onClick={addTask}>Add</button>
<button onClick={() => addTask(inputValue)}>Add</button>
</div>
<div className="task-list">
{tasks.length === 0 ? (
+40
View File
@@ -0,0 +1,40 @@
import { useEffect, useState } from "react";
import type { Task } from "../types/task";
export const useTasks = () => {
const [tasks, setTasks] = useState<Task[]>(() => {
const savedTasks = localStorage.getItem('tasks');
return savedTasks ? JSON.parse(savedTasks) : []
});
useEffect(() => {
localStorage.setItem('tasks', JSON.stringify(tasks));
}, [tasks]);
const addTask = (title: string) => {
if (title.trim() === '') return;
const newTask: Task = {
id: Date.now(),
title: title,
completed: false,
createdAt: new Date().toISOString()
};
setTasks([...tasks, newTask]);
setTasks(prev => [...prev, newTask]);
};
const deleteTask = (id: number) => {
setTasks(tasks.filter(task => task.id !== id));
}
const toggleTask = (id: number) => {
setTasks(tasks.map(task =>
task.id === id ? { ...task, completed: !task.completed } : task
));
}
return { tasks, addTask, deleteTask, toggleTask };
};