Reputation: 197
I started playing with Hooks and I have a useState object with multiple inputs. What I'd like to understand is how to clear the input value after submitting the form.
On the sumbit function I setInput({ Input1: "", Input2: "" });
and this actually cleans the object values but not the input values.
Also, not sure why console.log(input);
appears more than once.
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [input, setInput] = useState({ Input1: "", Input2: "" });
const [button, setButton] = useState("Button");
console.log(input);
const _handleChange = e => {
setInput({ ...input, [e.target.name]: e.target.value });
};
function _handleSubmit(e) {
e.preventDefault();
setInput({ Input1: "", Input2: "" });
setButton("Submitted");
setTimeout(() => setButton("Button"), 1000);
console.log("Submitted");
}
return (
<form onSubmit={_handleSubmit}>
<input
type={"text"}
placeholder={"Input1"}
name={"Input1"}
onChange={_handleChange}
/>
<input
type={"text"}
placeholder={"Input2"}
name={"Input2"}
onChange={_handleChange}
/>
<button text="Save" type="submit">
{button}
</button>
</form>
);
}
Upvotes: 1
Views: 5331
Reputation: 53994
Currently, your input
is an uncontrolled component, it doesn't aware of the state input.Input1
that handled by _handleChange
.
Try adding a value
prop to it.
<input value={input.Input1} onChange={_handleChange} />
Moreover, the log appears twice on _handleSubmit
because you changing the state twice:
setInput({ Input1: '', Input2: '' });
setButton('Submitted');
timeout
which changes the state after 1000ms
- causes a single render and second log. setTimeout(() => setButton('Button'), 1000);
Upvotes: 2