why globalId is incremented by 2 while I click only one time on Create Todo or submit the form. How to solve it

17 views Asked by At
import { useState } from 'react';
import './App.css';


let globalId = 0

function App(props) {
  const [todo,setTodo] = useState([])
  const [task,setTask] = useState("")
  function createTodo(event){
    event.preventDefault()  
    setTodo(oldTodo => {  
      setTask('')
        return [...oldTodo,{val:task,id:globalId++}]
      })
  }
  function deleteTodo(index){
    setTodo(oldTodo => oldTodo.filter(e => e.id !== index))
  }

  return (
    <>
      <h1>To Do App</h1>
      <form onSubmit={(e)=>createTodo(e)}>
        <input type='text' value={task} onChange={event => setTask(event.target.value)}/>
        <button type='submit'>Create Todo</button>
      </form>
      <ul>
        {
          todo.map((item)=>{
            return <li key={item.val}>{item.val} {item.id} <button onClick={()=>deleteTodo(item.id)} >Delete</button> </li>
          })
        }
      </ul>
    </>
  );
}


export default App;

Want globalId increment by 1 after submit or create, why globalId is incremented by 2 while I click only one time on Create Todo or submit the form. How to solve it

0

There are 0 answers