Skip to content

Commit ea98e96

Browse files
add localstorage
1 parent 2ff2071 commit ea98e96

File tree

2 files changed

+34
-6
lines changed

2 files changed

+34
-6
lines changed

src/App.css

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ hr+p {
9494
li {
9595
list-style-type: none;
9696
background: #f8f9fa;
97-
margin-bottom: 0.5rem;
97+
margin-bottom: 0.2rem;
9898
padding: 0.5rem 1rem;
9999
border-radius: 0.5rem;
100100
color: #222;

src/App.tsx

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
import { useReducer, useState } from 'react'
1+
import { useEffect, useReducer, useState } from 'react'
22
import './App.css'
3+
4+
const TODOS_STORAGE_KEY = 'todos'
35
interface Task {
46
id?: number;
57
text: string;
@@ -12,9 +14,22 @@ const App = () => {
1214
const [text, setText] = useState('');
1315
const [todos, dispatch] = useReducer(reducer, initialState)
1416

17+
useEffect(() => {
18+
const loadedTasks = loadTasks();
19+
if (loadedTasks.length > 0) {
20+
loadedTasks.forEach(task => {
21+
dispatch({ type: "ADD_TASK", text: task.text, done: task.done, id: task.id })
22+
})
23+
}
24+
}, [])
25+
26+
useEffect(() => {
27+
localStorage.setItem(TODOS_STORAGE_KEY, JSON.stringify(todos))
28+
}, [todos])
29+
1530
const handleAddTask = () => {
1631
if (!text) return
17-
dispatch({ type: 'ADD_TASK', value: text })
32+
dispatch({ type: 'ADD_TASK', text: text })
1833
setText('');
1934
}
2035

@@ -63,23 +78,36 @@ const App = () => {
6378
export default App
6479

6580
type Action =
66-
| { type: 'ADD_TASK', value: string }
81+
| { type: 'ADD_TASK', text: string, done?: boolean, id?: number }
6782
| { type: 'DELETE_TASK', id: number }
6883
| { type: 'TOGGLE_TASK', id: number }
6984

7085
const reducer = (state: Task[], action: Action) => {
7186
switch (action.type) {
7287

7388
case 'ADD_TASK':
74-
return [...state, { id: Date.now(), text: action.value, done: false }]
89+
return [...state, {
90+
id: action.id ?? Date.now(),
91+
text: action.text,
92+
done: action.done ?? false
93+
}]
7594

7695
case 'DELETE_TASK':
7796
return state.filter(task => task.id !== action.id)
7897

7998
case 'TOGGLE_TASK':
80-
return state.map(task => (task.id === action.id) ? { ...task, done: !task.done } : task)
99+
return state.map(task => (
100+
task.id === action.id) ? { ...task, done: !task.done } : task)
81101

82102
default:
83103
return state
84104
}
85105
}
106+
107+
const loadTasks = (): Task[] => {
108+
const savedTasks = localStorage.getItem(TODOS_STORAGE_KEY)
109+
if (savedTasks) {
110+
return JSON.parse(savedTasks)
111+
}
112+
return []
113+
}

0 commit comments

Comments
 (0)