0

I have a form with one input element. When the form is submitted, I want it to be pushed to the array of messages. This code does it only once. When the form is submitted for the second time, it only changes the value of the last message instead of adding a new value after it.

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

function App() {
  const chat = {
    messages: [
      {
        to: "John",
        message: "Please send me the latest documents ASAP",
        from: "Ludwig",
      },
    ],
  };
  const [form, setForm] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    chat.messages.push({
      message: `${form}`,
    });
    //this console.log below shows that the message from the form has been pushed successfully
    //however when the form is submitted again with a new value it just alters the above successfully pushed value
    //INSTEAD of adding a NEW value after it. The length of the array is INCREASED only once and that is the problem
    console.log(chat.messages);

    setForm("");
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={form}
          onChange={(e) => setForm(e.target.value)}
        />
      </form>
    </div>
  );
}

export default App;
2
  • chat is created afresh after every render. You can useRef here to persist values over render cycles. Commented Dec 21, 2021 at 18:26
  • state variables are also persisted over render cycles, but they cause rerender. Btw, I cannot see any API call in your code Commented Dec 21, 2021 at 18:27

1 Answer 1

1

chat needs to be a state variable. So you can use something like the follow:

import React, { useState, useEffect } from "react";

function App() {
  const [chat, setChat] = useState({
    messages: [
      {
        to: "John",
        message: "Please send me the latest documents ASAP",
        from: "Ludwig"
      }
    ]
  });
  const [form, setForm] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    setChat((prev) => ({
      messages: [
        ...prev.messages,
        {
          message: `${form}`
        }
      ]
    }));
    //this console.log below shows that the message from the form has been pushed successfully
    //however when the form is submitted again with a new value it just alters the above successfully pushed value
    //INSTEAD of adding a NEW value after it. The length of the array is INCREASED only once and that is the problem
    console.log(chat.messages);

    setForm("");
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={form}
          onChange={(e) => setForm(e.target.value)}
        />
      </form>
    </div>
  );
}

export default App;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.