diff --git a/TODO-LIST/src/hooks/useLocalStorage.js b/TODO-LIST/src/hooks/useLocalStorage.js new file mode 100644 index 0000000..b648561 --- /dev/null +++ b/TODO-LIST/src/hooks/useLocalStorage.js @@ -0,0 +1,24 @@ +import { useState, useEffect } from 'react' + +function useLocalStorage(key, initialValue) { + const [state, setState] = useState(() => { + try { + const stored = localStorage.getItem(key) + return stored ? JSON.parse(stored) : initialValue + } catch (e) { + return initialValue + } + }) + + useEffect(() => { + try { + localStorage.setItem(key, JSON.stringify(state)) + } catch (e) { + // ignore write errors (e.g., storage full, sandboxed env) + } + }, [key, state]) + + return [state, setState] +} + +export default useLocalStorage diff --git a/TODO-LIST/src/pages/Home.jsx b/TODO-LIST/src/pages/Home.jsx index 74b9c24..5584bfa 100644 --- a/TODO-LIST/src/pages/Home.jsx +++ b/TODO-LIST/src/pages/Home.jsx @@ -1,23 +1,19 @@ -import React,{useState,useEffect} from 'react' +import React,{useState} from 'react' import {nanoid} from 'nanoid' import Todo from '../components/Todo' - -const getTodos = () => { - let todos = localStorage.getItem('todos') - if (todos) { - return JSON.parse(todos) - } - return [] -} +import useLocalStorage from '../hooks/useLocalStorage' const Home = () => { - const [todos, setTodos] = useState(getTodos()) + const [todos, setTodos] = useLocalStorage('todos', []) const [todo, setTodo] = useState('') const addTodo = (e) => { e.preventDefault() - if (todo && todos.findIndex(t => t.text === todo) === -1) { - setTodos(prev => [...prev, {id:nanoid(),text:todo}]) + const normalized = todo.trim() + if (!normalized) return + const exists = todos.some(t => t.text.trim().toLowerCase() === normalized.toLowerCase()) + if (!exists) { + setTodos(prev => [...prev, {id: nanoid(), text: normalized}]) setTodo('') } } @@ -27,35 +23,30 @@ const Home = () => { } const moveUp = (id) => { - let index = todos.findIndex(t => t.id === id) + const index = todos.findIndex(t => t.id === id) if (index > 0) { - let temp = todos[index] - todos[index] = todos[index - 1] - todos[index - 1] = temp - setTodos([...todos]) + const next = [...todos] + ;[next[index - 1], next[index]] = [next[index], next[index - 1]] + setTodos(next) } } const moveDown = (id) => { - let index = todos.findIndex(t => t.id === id) - if (index < todos.length - 1) { - let temp = todos[index] - todos[index] = todos[index + 1] - todos[index + 1] = temp - setTodos([...todos]) + const index = todos.findIndex(t => t.id === id) + if (index < todos.length - 1 && index !== -1) { + const next = [...todos] + ;[next[index + 1], next[index]] = [next[index], next[index + 1]] + setTodos(next) } } - useEffect(() => { - localStorage.setItem('todos', JSON.stringify(todos)) - },[todos]) return (