Karan
Karan

Reputation: 181

Pushing form data to an array of objects

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;

Upvotes: 0

Views: 1438

Answers (1)

Marco Nisi
Marco Nisi

Reputation: 1241

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;

Upvotes: 1

Related Questions