import React, {useState, useEffect} from "react"; // get local data let getLocaleData = () => { const taskList = localStorage.getItem('myTodoKey'); if(taskList){ return JSON.parse(taskList); // JSON.parse() will work for converting string into array } else{ return []; } } let Todo = () => { const [todo, setTodo] = useState("Homework"); const [items, setItems] = useState(getLocaleData()); const [editItem, setEditItem] = useState(''); const [editBtn, setEditBtn] = useState(false); // add todo const addItem = () => { if(!todo){ alert('Plz fill the data'); } else{ // add todo with unique id const getIdItem = { id: new Date().getTime().toString(), name: todo } setItems([...items, getIdItem]); setTodo(''); } } // edit button creation const editItems = () => { if(todo && editBtn){ setItems( items.map((curEle) => { if(curEle.id === editItem){ return {...curEle, name: todo} } return curEle; }) ); setTodo(''); setEditItem(null); setEditBtn(false); } } // delete todo const deleteElement = (elementId) => { const deleteItems = items.filter((curEle) => { return curEle.id !== elementId; }); setItems(deleteItems); } // edit todo const editElement = (elementId) => { const editedItem = items.find((curEle) => { return curEle.id === elementId; }); setTodo(editedItem.name); setEditItem(elementId); setEditBtn(true); } // remove all const removeAll = () => { setItems([]); } // Store data in local storage useEffect(() => { localStorage.setItem('myTodoKey', JSON.stringify(items)); }, [items]); const style = { color: 'white', background: 'black', padding:'10px', width: '350px', marginTop: '15px', borderRadius: '16px', height: '46px' } const inputStyle = { border: '1px solid #333', borderRadius: '10px', paddingLeft: '10px', width: '250px', outline: 'none', height: '40px', } const btn = { background: 'orange', borderRadius: '10px', color: 'white', paddingTop: '6px', paddingBottom: '6px', border: 'none', paddingLeft: '15px', paddingRight: '15px', width: '80px' } return( <> <center><br/> <h2>Todo Lists</h2><br/> <input style={inputStyle} type="text" id="add_todo" placeholder="Enter any keywords" value={todo}onChange={(e) =>setTodo(e.target.value)}/> { editBtn ? (<button style={btn} onClick={editItems}>Edit</button>) : (<button style={btn} onClick={addItem}>Add</button>) } <div id="todoList"> { items.map((curEle, index) => { return ( <> <divstyle={style}> <span style={{float:'left', color:'yellow'}}>{curEle.name}</span> <span style={{float:'right', color:'green', cursor:'pointer'}} onClick={() => {editElement(curEle.id)}}>edit</span> <spanstyle={{float:'right', color:'red', marginRight:'10px', cursor:'pointer'}} onClick={() => {deleteElement(curEle.id)}}>Delete</span> </div> </> ) }) }<br/> <button style={{width:'120px', background:'purple', border:'none', borderRadius:'20px', padding:'5px 6px 6px 5px', color:'white', marginLeft:'-60px'}} onClick={removeAll}>Remove All</button> </div> </center> </> ) } export default Todo;
