Reputation: 143
I am building a signup form containing multiple inputs(username, date of birth, etc). After a form is submitted it is stored somewhere containing a list of previous submitted forms.
Link to working sample: https://codesandbox.io/s/react-form-multiple-storage-xcmt3i?file=/src/App.js
Codebase for working sample:
import React, { useState } from "react";
const App = () => {
const [values, setValues] = useState({
userName: "",
dateOfBirth: ""
});
const [submissions, setSubmission] = useState([
{
userName: "april123",
dateOfBirth: "2000-01-01"
}
]);
const addSubmission = (values) => {
const newSubmissions = [...submissions, { values }];
setSubmission(newSubmissions);
console.log(submissions);
};
const handleChange = (event) => {
const value = event.target.value;
setValues({
...values,
[event.target.name]: value
});
};
const handleSubmit = (event) => {
event.preventDefault();
addSubmission(values);
};
return (
<>
<form onSubmit={handleSubmit}>
<h1> Signup Form </h1>
<div>
<label>username</label>
<input
type="text"
name="userName"
onChange={handleChange}
value={values.userName}
required
/>
</div>
<div>
<label>Date of Birth</label>
<input
type="date"
name="dateOfBirth"
onChange={handleChange}
value={values.dateOfBirth || ""}
/>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
</>
);
};
export default App;
Questions:
addSubmission
setup properly for what I am trying to achieve? Or can it be improved?console.log()
placement, why am I only seeing previous submissions
and not current? Screenshot below for details.Upvotes: 0
Views: 1232
Reputation: 96
const newSubmissions = [...submissions, values];
You should also clear the current state values after you have successfully submitted an entry.
Upvotes: 1