1
function handleChange(event) {
    event.preventDefault()
    setNewItem(event.target.value)
}

In this function, I want to give every todo element a new and unique id.

function addTodo(event) {
    event.preventDefault()
    setNewItem({ id: 0 })
    setTodosList(prevList => [...prevList, newItem])
    setNewItem("");
    inputRef.current.focus()
    if (newItem === "") {
        alert("Plese Write an todo");
    }
}

function removeTodo() {
    // setTodosList(prevItems => prevItems.filter(item => item.id !== id))
}

const allTodos = todosList.map(item => (
    <li key={item}>
        {item}
        <i className="ri-delete-bin-line del" onClick={removeTodo}></i>
    </li>
));

Here all my code is running.

<header>
    <img src={require('./images/todo.png')} alt="Todo-Logo" width="100" height="100" />
    <h1 className="title">My Todo App</h1>
</header>
<div className="container">
    <br />
    <form>
        <div className="input-btnFlex">
            <input
                type="text"
                placeholder="Write Your Todo "
                name="newItem"
                ref={inputRef}
                value={newItem}
                onChange={handleChange}
            />
            <button className="ri-add-circle-fill add-btn" onClick={addTodo}></button>
        </div>
    </form>
    <div>
        <ul>
            {allTodos}
        </ul>
    </div>
</div>
M0nst3R
  • 5,186
  • 1
  • 23
  • 36
Muneeba Dilawaze
  • 105
  • 2
  • 11
  • 2
    Duplicate of [create unique id with javascript](https://stackoverflow.com/questions/3231459/create-unique-id-with-javascript) see also https://www.google.com/search?q=site%3Astackoverflow.com+javascript+generate+unique+id – Guy Incognito Jun 17 '20 at 07:40
  • If you are not persisting the todos in localstorage you can use the following: `const createId = ((id) => () => id++)(1);const id = createId()` – HMR Jun 17 '20 at 07:44
  • Why do you want to add the IDs? What will you be using them for? – M0nst3R Jun 17 '20 at 07:47

3 Answers3

1

create a local variable id and every time you need a new id just increment the id.. Otherwise i would recommend assign Date.now() as the id as it will never have a duplicate value

Other Method [Not Recommended] only use this if absolutely necessary: if you are using a list use the index of list as id..

Prabodh
  • 165
  • 2
  • 12
1

Here are some options that can be used for ids:

  • Date/Time Stamp.
  • Any unique id generator for javascript like UUID
  • Create your own random id generator function using Math.random()
  • You can create your own custom id string using index
Rohit Omar
  • 11
  • 2
0

You can time stamp

If a real human user is creating todo's one after another you can use a timestamp as an identifier since it will always be different each time and will stay the same no matter the order.

  • Always unique
  • Hard to guess
  • Always sequential
setNewItem({ id: Date.now().toString() })
Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81