Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export const Todo = () => {
- const [text, setText] = useState('');
- const [list, setList] = useState([]);
- function onChangeText(e) {
- setText(e.target.value);
- }
- function addTask() {
- /**
- * Use setState callback to safely access the current state
- * use the current list's length to generate the id
- */
- setList((current) => [...current, { id: current.length, title: text }]);
- /**
- * Clear the input after adding the task
- */
- setText('');
- }
- function deleteTask(id) {
- /**
- * Use setState callback to safely access the current state
- * filter the list to remove the item with the id
- * then map the list to update the ids to avoid future ID collisions
- * since we use the list length to generate the id if we had a list of
- * [{ id: 0, title: 'task 1' }, { id: 1, title: 'task 2' }] and then we
- * delete the first item the list would be [{ id: 1, title: 'task 2' }]
- * and the next time we add an item length would be 1 and the id would be 1
- * so we would have 2 items with the same id.
- * To avoid this we map the list to update the ids after filtering the list
- *
- * This is a good reason to not use list length to generate ids
- * there is no real reason to have auto incrementing ids in the todo list
- * consider using a uuid library to generate unique ids instead
- */
- setList((current) =>
- current
- .filter((item) => item.id !== id)
- .map((item, index) => ({ ...item, id: index + 1 })
- );
- }
- return (
- <>
- <label htmlFor="item">Type item here: </label>
- {
- /**
- * Use a controlled component for the input to avoid
- * having to use a dom selector to get the current value for saving a todo
- */
- }
- <input
- type="text"
- id="input-textbox"
- onChange={onChangeText}
- value={text}
- />
- <div>
- {/**
- * disable the button if there's no text in the input
- * to avoid adding empty todo item
- */}
- <button disabled={Boolean(text.length)} onClick={addTask}>Add task button</button>
- {list.map((item) => {
- return (
- <div>
- {item.id} : {item.title}
- <button onClick={() => deleteTask(item.id)}>delete</button>
- </div>
- );
- })}
- </div>
- </>
- );
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement