Skip to content
Advertisement

Remix useSubmit arbitrary data

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement