I have an Ant form in a React app, where some fields are required and some not. My problem is that when not required field is empty, backend sends the validation error. My question is, is there a way to NOT TO SEND the value of not required field if there is no value?
Screenshot of the current object that is sent:
My code for form submission:
const submitHandler = async (val: any) => {
setLoading(true);
try {
let res: any = await API.put(`recipients/${pid}`, {
...val,
user_id: loggedInUser.id,
type: type,
});
setLoading(false);
message.success("Benutzer erfolgreich aktualisiert");
setError("");
} catch (error: any) {
setLoading(false);
setError(error?.response.data.message);
message.error(error?.response.data.message);
}
};
idk about typescript, but this is how i would do in javascript:
const submitHandler = async (val: any) => {
...
for (let key in val) {
if(!val[key]) delete val[key];
}
...
};
You can remove properties with empty value from that val
before sending it to the back end. A way is doing it so:
let res = await API.put(`recipients/${pid}`, {
...Object.fromEntries(Object.entries(val).filter(([_, v]) => v)),
user_id: loggedInUser.id,
type: type,
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.