We have the following form.
const MyForm = ({
myFormRef,
}) => (
<form id="myForm" ref={myFormRef} method="POST">
<input name="request_token" type="hidden" />
<input name="id" type="hidden" />
<input name="versionId" type="hidden" />
<input name="additionalId" type="hidden" />
</form>
);
export default MyForm;
We are using useRef hook to reference this form and calling it within another Component as follows.
const myFormRef = useRef();
<MyForm
myFormRef={myFormRef}
/>
The postData
function at the end is in a js file.
Question is on this postData
function.
This is triggered when a form is submitted via a button click.
It is all working fine where I am capturing correct details and able to submit the form.
The issue:
It is the format of how I am sending the data over which is the issue.
I am sending over details in following format in this form.
{
token,
id,
versionId,
additionalId
}
Instead I want to send it as:
{
token,
overallData: {
id,
versionId,
additionalId
}
}
How can I modify the request format to wrap inside overallData for the 3 fields (token is still outside) before submitting?
export const postData = (
myFormRef,
token,
myLink,
id,
versionId,
additionalId
) => {
const fields = {
request_token: token,
id,
versionId,
additionalId,
};
// checking if data exists for a key (example id or token) and remove if no value against the key.
[...myFormRef.current.children].forEach((child) => {
child.value = fields[child.name];
if (!child.value) {
myFormRef.current.removeChild(child);
}
});
// then submit
myFormRef.current.action = myLink;
myFormRef.current.submit();
};
Note: I have to stick with this style to use the form and useRef() due to other dependencies.
Thus looking for a way to possibly modify postData. Else advise other options. Thanks.