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.
JavaScript
x
30
30
1
export const action: ActionFunction = async (request) => {
2
// I want access to {arbitraryData} here passed from submit
3
}
4
5
export default function EditSlug() {
6
const post = useLoaderData();
7
8
// ...Submit handler passing arbitrary data (post.title in this case)
9
const handleSubmit = (event: any) => {
10
submit(
11
{ target: event?.currentTarget, arbitraryData: post.title },
12
{ method: "post", action: "/admin/edit/{dynamicRouteHere}" }
13
);
14
};
15
16
return(
17
<Form method="post" onSubmit={handleSubmit}>
18
<p>
19
<label>
20
Post Title:
21
<input
22
type="text"
23
name="title"
24
value={post.title}
25
disabled
26
readOnly
27
/>
28
</label>
29
</p>
30
Is there a way to receive custom data in my action using handleSubmit?
Advertisement
Answer
Another way to do this is
JavaScript
1
35
35
1
export const action: ActionFunction = async (request) => {
2
// I want access to {arbitraryData} here passed from submit
3
// Now u can get this in formData.
4
}
5
6
export default function EditSlug() {
7
const post = useLoaderData();
8
const formRef = useRef<HtmlFormElement>(null); //Add a form ref.
9
// ...Submit handler passing arbitrary data (post.title in this case)
10
const handleSubmit = (event: any) => {
11
12
const formData = new FormData(formRef.current)
13
formData.set("arbitraryData", post.title)
14
15
submit(
16
formData, //Notice this change
17
{ method: "post", action: "/admin/edit/{dynamicRouteHere}" }
18
);
19
};
20
21
return(
22
<Form ref={formRef} method="post" onSubmit={handleSubmit}>
23
<p>
24
<label>
25
Post Title:
26
<input
27
type="text"
28
name="title"
29
value={post.title}
30
disabled
31
readOnly
32
/>
33
</label>
34
</p>
35
In this way, you are altering the original formData and adding another key to it and using that to submit the form.