Reputation: 181
In the tutorials I've found, the best way to capture forms inputs, is to use a "onchange" handler. However, how should we deal with fields that are left to the default value ?
For example in something like the example below, if "country" is left to the default value, the "formData" will never get it.
const [formData, setFormData] = useReducer(formReducer, {});
const handleChange = event => {
setFormData({
name: event.target.name,
value: event.target.value,
});
}
const handleSubmit = event => {
event.preventDefault();
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
};
fetch('http://0.0.0.0:8000/add_user/', requestOptions)
}
<form onSubmit={handleSubmit}>
<fieldset>
<input type="text" name="name" placeholder="Name" onChange={handleChange} />
<input type="text" name="country" value="" onChange={handleChange} required />
</fieldset>
<Button type="submit">Submit</Button>
</form>
I've thought about some solutions but I don't think they are the best practices. For example, adding a snippet of code that manually assigns all default values to the form in the construction, so the formData is pre-filled. Is there a clean & nice way to do it ?
Upvotes: 0
Views: 286
Reputation: 439
In your useReducer
hook you should store initial country value and then assign it to the value in country input, like below:
const [formData, setFormData] = useReducer(formReducer, { country: "" });
<form onSubmit={handleSubmit}>
<fieldset>
<input type="text" name="name" placeholder="Name" onChange={handleChange} />
<input type="text" name="country" value={formData.country} onChange={handleChange} required />
</fieldset>
<Button type="submit">Submit</Button>
</form>
Upvotes: 1