Home > Enterprise >  Encountring very fundamental problem with react, why item.id in my case is increasing by 2?
Encountring very fundamental problem with react, why item.id in my case is increasing by 2?

Time:05-14

hi i have just started learning react and facing problems in understanding fundamentals , here i am creating basic todo app question is why item-id in seq of 1,3,5,7.... as show in image attached How do i slove this ?

import { useState } from "react";
import "./App.css";

let counter = 0;

function App() {
 const [text, setText] = useState("");
 const [todos, setTodos] = useState([]);

const createTodo = (e) => {
  e.preventDefault();
  setText('')
  setTodos((oldTodos) => [...oldTodos, { todo: text, id: counter   }]);
};

 return (
   <div className="App">

     <form onSubmit={createTodo}>
     <input
      type="text"
      value={text}
      onChange={(e) => setText(e.target.value)}
     ></input>
     <button type="submit">Add Todo</button>
     </form>

   <ul>
    {todos.map((item) => {
      return (
        <li key={item.id}>
          {item.todo}-{item.id}
        </li>
      );
    })}
  </ul>

 </div>
 );
}

export default App;

browser output [output in browser1

Any better approach to slove issue??

CodePudding user response:

try this code instead

 const [text, setText] = useState("");
 const [todos, setTodos] = useState([]);
 const [count , setCount] = useState(0);

const createTodo = (e) => {
  e.preventDefault();
  setCount(count  )
  setText('')
  setTodos((oldTodos) => [...oldTodos, { todo: text, id: count }]);
};

CodePudding user response:

counter means you are re-assigning the value of the counter variable. counter = counter 1, counter = 1 are alternatives for it. So what you can try is you can first change the value of the variable and then assign it to the id property.

let counter = 0;

function App(){
    const [text, setText] = useState("");
    const [todos, setTodos] = useState([]);

    const createTodo = (e) => {
        e.preventDefault();
        setText('');
        counter  ; // or counter  = value or counter = counter   value;
        setTodos((oldTodos) => [...oldTodos, { todo: text, id: counter }]);
    };

}
  • Related