0

I am building a todo app and my form has an input element in it where the value is stored in a state variable. The form should submit that value to an array but when I press submit it doesn't show and only shows the value when I try to submit another value., and so on and so on.

import React, { useState } from "react";

function App() {
  const [inputValue, setInputValue] = useState("");
  const [todos, setTodos] = useState([]);

  const handleSubmit = (e) => {
    e.preventDefault();
    const name = inputValue;
    if (name === "") return;
    setTodos((prevTodos) => {
      return [...prevTodos, { id: name, name: name, isComplete: false }];
    });
    console.log(todos);
    setInputValue("");
  };
  return (
    <main>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          className="todo-input"
          placeholder="Create a new todo..."
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
      </form>
    </main>
  );
}

export default App;
  • can you tell us where did you write the code to show `todos`? – Pradip Dhakal Nov 25 '21 at 12:17
  • just a simple project I want to make,to learn more about code – KrokeWaan Nov 25 '21 at 12:19
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Pradip Dhakal Nov 25 '21 at 12:20
  • Your question is a duplicate of this question. please look into it: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Pradip Dhakal Nov 25 '21 at 12:20

1 Answers1

0

Your code works as expected. Your todos array is updated in the onSubmit function, however, you are not able to view this change.

If you wrote:

useEffect(() => console.log(todos), [todos])

You'll see 'todos' updating as you'd expect