Reputation: 1
i have this form and when i send it i want to reset it, but the value of the select and an input depend on a State. when i reset it the select has the value this is an example, I am using dynamic inputs so I cannot set the value of the inputs manually.
import {
FormEvent,
useState,
} from "react";
import "./styles.css";
export default function App() {
const [variable, setVariable] = useState("0");
const handleChange = (event) => {
setVariable(event.target.value);
};
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
event.currentTarget.reset();
};
return (
<form onSubmit={handleSubmit}>
<select onChange={handleChange} value={variable} defaultValue={variable}>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" value={variable} />
<input defaultValue={"for check reset"}></input>
<input type="submit" />
</form>
);
}
https://codesandbox.io/p/sandbox/form-sync-select-reset-ts-m57lkh?file=%2Fsrc%2FApp.tsx%3A8%2C37
I tried with the value, with the defaultValue, with the defaultChecked and with the option "selected= {variable === value}" but nothing worked. I want to avoid using an external library
Upvotes: 0
Views: 26
Reputation: 165
How about just resetting through the setter function for "variable" inside the handleSubmit call?
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setVariable("0")
};
I suppose you want to send this somewhere? In that case you could either call upon your api directly and follow up with the reset or delay it upon success by passing that action async to .then...
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
yourApiCall().then(() => {setVariable("0")})
};
Upvotes: 0