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;
CodePudding user response:
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;