7

I read up on the Remix docs on action and most of information I can find on action is it uses the the form POST with button submit to trigger the action

export default function Game() {
    const counter = useLoaderData();

    return (
        <>
            <div>{counter}</div>
            <div>
                <Form method="post">
                    <button type="submit">click</button>
                </Form>
            </div>
        </>
    );
}

However, how would the action be triggered in regards to something else like... drag and drop components, where after dropping it should trigger the action post

LuxuryWaffles
  • 1,518
  • 4
  • 27
  • 50

1 Answers1

8

useSubmit should do what you want.

An example from the docs

import { useSubmit, useTransition } from "remix";

export async function loader() {
  await getUserPreferences();
}

export async function action({ request }) {
  await updatePreferences(await request.formData());
  return redirect("/prefs");
}

function UserPreferences() {
  const submit = useSubmit();
  const transition = useTransition();

  function handleChange(event) {
    submit(event.currentTarget, { replace: true });
  }

  return (
    <Form method="post" onChange={handleChange}>
      <label>
        <input type="checkbox" name="darkMode" value="on" />{" "}
        Dark Mode
      </label>
      {transition.state === "submitting" ? (
        <p>Saving...</p>
      ) : null}
    </Form>
  );
}
Morse
  • 695
  • 8
  • 8
Can Rau
  • 3,130
  • 1
  • 23
  • 33
  • 2
    link to the doc https://remix.run/docs/en/v1/api/remix#usesubmit – Lorezz Apr 22 '22 at 10:19
  • 1
    Thanks @Lorezz though link is already in the answer "Here's an example from the docs" – Can Rau Apr 22 '22 at 17:30
  • Any idea if useTransition works without JavaScript (in case user has us turned off or is doesn’t load) – user1275105 Jul 28 '22 at 22:55
  • I'm pretty sure it can't work without JS like any other AJAX like behaviour. So if the JS failed for whatever reason the form will be submitted using the normal browser behavior and reloading the page. – Can Rau Aug 10 '22 at 14:59
  • how can I do this form post but without a navigate to the specified action? I have a login modal in `/otherpage` whose action points to `/?index` but it navigates to `/` – David Rearte Sep 15 '22 at 21:05
  • @DavidRearte If I understand your question correctly one way could be using `useFetcher` – Can Rau Oct 01 '22 at 14:59
  • 1
    @CanRau yes that did the trick, thx – David Rearte Oct 03 '22 at 02:04