I showed the refctor version where I use only one useState hook
Three useState ()
importReact,{useState}from'react';// Define the type for a TodointerfaceTodo{id:number;title:string;}constdefaultTodos=[{id:123456789,title:"Bappa Saha Bapi"},{id:12345678900,title:"Partho Saha Bapi"}]constBasicTodo=()=>{const[todos,setTodos]=useState<Todo[]>(defaultTodos);const[title,setTitle]=useState<string>('');const[editId,setEditId]=useState<number|null>(null);// Function to add or update a todoconsthandleSubmit=(e:React.FormEvent<HTMLFormElement>)=>{e.preventDefault();if (editId!==null){// Update existing todosetTodos(todos.map(todo=>(todo.id===editId?{...todo,title}:todo)));setEditId(null);}else{// Add new todoconstnewTodo:Todo={id:Date.now(),title};setTodos([...todos,newTodo]);}setTitle('');};// Function to delete a todoconsthandleDelete=(id:number)=>{setTodos(todos.filter(todo=>todo.id!==id));};// Function to edit a todoconsthandleEdit=(todo:Todo)=>{setTitle(todo.title);setEditId(todo.id);};return (<divstyle={{padding:'20px'}}><h1>TodoList</h1>
<formonSubmit={handleSubmit}><inputtype="text"value={title}onChange={(e)=>setTitle(e.target.value)}placeholder="Enter todo title"required/><buttontype="submit">{editId!==null?'Update':'Add'}</button>
</form>
<ul>{todos.map(todo=>(<likey={todo.id}>{todo.title}{""}<buttononClick={()=>handleEdit(todo)style={{padding:'5px 20px',margin:'10px'}}}>Edit</button>
<buttononClick={()=>handleDelete(todo.id)}style={{padding:'5px 20px'}}>Delete</button>
</li>
))}</ul>
</div>
);};exportdefaultBasicTodo;
🔥 Refactor One useState ()
importReact,{useState}from'react';constApp=()=>{// State to hold todos and input fields in one objectconst[state,setState]=useState({todos:[],title:'',editId:null,});// Function to add or update a todoconsthandleSubmit=(e)=>{e.preventDefault();const{todos,title,editId}=state;if (editId!==null){// Update existing todosetState({...state,todos:todos.map(todo=>(todo.id===editId?{...todo,title}:todo)),title:'',editId:null,});}else{// Add new todoconstnewTodo={id:Date.now(),title};setState({...state,todos:[...todos,newTodo],title:'',});}};// Function to delete a todoconsthandleDelete=(id)=>{setState({...state,todos:state.todos.filter(todo=>todo.id!==id),});};// Function to edit a todoconsthandleEdit=(todo)=>{setState({...state,title:todo.title,editId:todo.id,});};return (<divstyle={{padding:'20px'}}><h1>TodoList</h1>
<formonSubmit={handleSubmit}><inputtype="text"value={state.title}onChange={(e)=>setState({...state,title:e.target.value})}placeholder="Enter todo title"required/><buttontype="submit">{state.editId!==null?'Update':'Add'}</button>
</form>
<ul>{state.todos.map(todo=>(<likey={todo.id}>{todo.title}<buttononClick={()=>handleEdit(todo)}>Edit</button>
<buttononClick={()=>handleDelete(todo.id)}>Delete</button>
</li>
))}</ul>
</div>
);};exportdefaultApp;
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)