0

I am trying to save the input from a form inside an array using useState. I created a function for clicking an Add button, but the onChange input is not added to the notes array when I click the button. Empty array in the console log. Please be kind enough to point out the problem.

const {useState} = React;

function CreateArea() {
  const [newNote, setNote] = useState({
    title: "",
    content: "",
  });

  const [notes, setNotes] = useState([]);
  console.log(notes);

  function addNote() {
    setNotes((prevNote) => {
      return [...prevNote, newNote];
    });
  }

  function handleChange(event) {
    const { value, name } = event.target;
    setNote((prevValue) => {
      return {
        ...prevValue,
        [name]: value,
      };
    });
  }

  return (
    <div>
      <form>
        <input
          onChange={handleChange}
          name="title"
          placeholder="Title"
          value={newNote.newTitle}
        />
        <textarea
          onChange={handleChange}
          name="content"
          placeholder="Take a note..."
          value={newNote.newContent}
          rows="3"
        />
        <button onClick={addNote}>Add</button>
      </form>
    </div>
  );
}


ReactDOM.render(<CreateArea />, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
champer
  • 21
  • 6
  • 1
    I just ran this code exactly and the only issue I found was not calling `event.preventDefault()` in the submit function which causes a page refresh. After adding that the array is populated with the new note. This does not sound like what you're describing, so please include any other relevant details or clarify what your problem actually is. – Brian Thompson Mar 25 '22 at 13:38
  • 1
    You've been hit by the weird default of the `button` element: Its `type` attribute defaults to `submit`, so when it's in a `form` element, it submits the form. Your page gets refreshed as a result. The solution is: put `type="button"` on the button (giving us the absurd `` markup, but such is HTML). If I do that in the Stack Snippet I just copied your code into in the question, I see the notes get updated as you'd expect. – T.J. Crowder Mar 25 '22 at 13:39
  • 1
    @BrianThompson - Heh, I noticed the same thing. I think if it refreshes fast enough, that might account for what the OP sees. – T.J. Crowder Mar 25 '22 at 13:40

0 Answers0