feat(storage): persist task to localStorage using useEffect and lazy init
This commit is contained in:
+10
-2
@@ -1,11 +1,19 @@
|
|||||||
import { useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import type { Task } from "./types/task";
|
import type { Task } from "./types/task";
|
||||||
import { TaskItem } from "./components/TaskItem";
|
import { TaskItem } from "./components/TaskItem";
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
const [tasks, setTasks] = useState<Task[]>(() => {
|
||||||
|
const savedTasks = localStorage.getItem('tasks');
|
||||||
|
return savedTasks ? JSON.parse(savedTasks) : []
|
||||||
|
});
|
||||||
|
|
||||||
const [inputValue, setInputValue] = useState<string>('');
|
const [inputValue, setInputValue] = useState<string>('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
localStorage.setItem('tasks', JSON.stringify(tasks));
|
||||||
|
}, [tasks]);
|
||||||
|
|
||||||
const addTask = () => {
|
const addTask = () => {
|
||||||
if (inputValue.trim() === '') return;
|
if (inputValue.trim() === '') return;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user