I am trying to submit a form using Remix's useSubmit hook. But I want to be able to pass arbitrary data along with my form submit data.
I have form elements with some static values that have disabled/readonly attributes, which means their value will be null on form submission. However I have access to their actual values in my post variable, which I want to send to my action.
export const action: ActionFunction = async (request) => {
// I want access to {arbitraryData} here passed from submit
}
export default function EditSlug() {
const post = useLoaderData();
// ...Submit handler passing arbitrary data (post.title in this case)
const handleSubmit = (event: any) => {
submit(
{ target: event?.currentTarget, arbitraryData: post.title },
{ method: "post", action: "/admin/edit/{dynamicRouteHere}" }
);
};
return(
<Form method="post" onSubmit={handleSubmit}>
<p>
<label>
Post Title:
<input
type="text"
name="title"
value={post.title}
disabled
readOnly
/>
</label>
</p>
Is there a way to receive custom data in my action using handleSubmit?
Another way to do this is
export const action: ActionFunction = async (request) => {
// I want access to {arbitraryData} here passed from submit
// Now u can get this in formData.
}
export default function EditSlug() {
const post = useLoaderData();
const formRef = useRef<HtmlFormElement>(null); //Add a form ref.
// ...Submit handler passing arbitrary data (post.title in this case)
const handleSubmit = (event: any) => {
const formData = new FormData(formRef.current)
formData.set("arbitraryData", post.title)
submit(
formData, //Notice this change
{ method: "post", action: "/admin/edit/{dynamicRouteHere}" }
);
};
return(
<Form ref={formRef} method="post" onSubmit={handleSubmit}>
<p>
<label>
Post Title:
<input
type="text"
name="title"
value={post.title}
disabled
readOnly
/>
</label>
</p>
In this way, you are altering the original formData and adding another key to it and using that to submit the form.
(For what it's worth, readonly inputs are sent to the form, while disabled are not, so maybe you can use only readOnly)
To submit arbitrary data to an action, you can use hidden inputs:
<Form method="post" onSubmit={handleSubmit}>
<p>
<label>
Post Title:
<input
type="text"
name="title"
value={post.title}
disabled
readOnly
/>
<input type="hidden" name="title" value={post.title} />
</label>
</p>