'How to render only the new submission using form in React instead of showing the previous submissions as well?
I was working on a multiple input form where we submit the query, and the submitted query is displayed. After submission, all the fields go back to being blank. If I make another submission for another field, the display shows the new submission, but also shows the value for the previous submission of the previous field. I am not sure if I'm explaining it right. I'm still having a hard time understanding a lot of concepts within react. Here's my Form code:
export default function Form({searchQuery}) {
const [query, setQuery] = useState({
firstName: "",
lastName: "",
});
const handleChange = (event) => {
setQuery({ ...query, [event.target.name]: event.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
searchQuery(query);
setQuery({ firstName: "", lastName: "",});
};
return (
<div className="form-container">
<form onSubmit={handleSubmit}>
<div>
<input
type="text"
name="firstName"
placeholder="Search by First Name"
value={query.firstName}
onChange={handleChange}
/>
</div>
<div>
<input
type="text"
name="lastName"
placeholder= "Search by Last Name"
value={query.lastName}
onChange={handleChange}
/>
<div>
<button>Search</button>
</div>
</form>
</div>
);
}
And here's the component that shows displays these queries:
function SubmittedData()
{
const [query, setQuery] = useState([
{firstName: "",
lastName: "",
}]);
const searchQuery = (query1) => {
setQuery([
{
firstName: query1.firstName,
lastName: query1.lastName,
}
]);
};
return (
<div className="App">
<FormMemberSearch searchQuery ={searchQuery} />
{
query.map(query =>
{
return (
<div>
{query.firstName} {query.lastName}
</div>
) })
}
</div>
);
}
export default SubmittedData;
When I submit "Ana" for the first name, and leave the LastName field empty, it just shows Ana. If I enter Celly for the first name, it will only show Celly, which is fine. But after that submission, if I enter something like "Delvey" for the last name and submit the form, the result will have Celly Delvey. How do I get it to show only Delvey instead of the value of another field from the previous submission?
Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
