skip to Main Content

Whenever i tried to put something in my todoList there’s alwasy an empty element at first indext Why it is happening?

const [todoList, setTodoList] = useState([]);
  
  const addToList = (inputText) => {
    if (inputText === "") {
      alert("List is Empty")
    }else{
       setTodoList([inputText, ...todoList])
    }
    console.log(todoList);
  };

  const addList = (inputText) => {
    addToList(inputText);
  };
const [todoList, setTodoList] = useState([]);
  

  const addToList = (inputText) => {
    if (inputText === "") {
      alert("List is Empty")
    }else{
       setTodoList([...todoList, inputText])
    }
    console.log(todoList);
  };

  const addList = (inputText) => {
    addToList(inputText);
  };

i tried it also but it’s not working

2

Answers


  1. Your

    setTodoList([inputText, ...todoList])
    

    is taking the todoList using closure, so it is taking the same one every time.

    You need to do something like:

    setTodoList(todoList => [inputText, ...todoList])
    
    Login or Signup to reply.
  2. I think adding useEffect() might do the trick:

    const [todoList, setTodoList] = useState([]);
    
    const addToList = (inputText) => {
      if (inputText === "") {
        alert("List is Empty");
      } else {
        setTodoList([inputText, ...todoList]);
      }
    };
    
    useEffect(() => {
      console.log(todoList);
    }, [todoList]);
    
    const addList = (inputText) => {
      addToList(inputText);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search