Using an action of a page inside another page #10223
Replies: 2 comments 1 reply
-
It should work as long as you send the same request body, url and route params the second action needs. Usually the recommended approach is to move to a function the logic you want to re-use and call that in both actions. Or just point the form to that route action using the action prop so it sends the request there. |
Beta Was this translation helpful? Give feedback.
-
you will end up with awkward situation, where you have your form input (names) in multiple files and the loader in one and they will get out of sync, etc. So its simpler to co-locate the form you want to reuse and the function to handle the form. This way you see the input names and the form of the component and the function to handle it in one place. // somewhere/my-form.tsx
import {Form} from "@remix-run/react"
export const MyForm: React.FC = () => {
return (
<Form method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<button>send</button>
</Form>
)
} // somewhere/my-form.server.ts
export function handleMyForm(form: FormData) {
const foo = form.get("foo")
const bar = form.get("bar")
// ... do something
// ... return result
} Then in your action on any route you could: // any route
import {handleMyForm} from "somewhere/my-form.server.ts"
export async function action({request}: LoaderFunctionArgs) {
const form = await request.formData()
const result = handleMyForm(form)
// ...
} This way you could, if you wanted, handle multiple forms on a single page too. This is a trivial example, but you could use fetcher in the It also allows you to scope forms, both processing serverside and on component level: // somewhere/my-form.server.ts
export function handleMyForm(form: FormData, scope = "") {
const foo = form.get(scope + ".foo")
const bar = form.get(scope + ".bar")
// ... do something
// ... return result
} // somewhere/my-form.tsx
import {Form} from "@remix-run/react"
export const MyForm: React.FC<{scope: string}> = ({scope = ""}) => {
return (
<Form method="post">
<input type="text" name={scope + ".foo"} />
<input type="text" name={scope + ".bar"} />
<button>send</button>
</Form>
)
} |
Beta Was this translation helpful? Give feedback.
-
Inside a route, I'd like to define a loder and/or an action directly importing the one of another's.
E.g.
where psUtilsLoader would be the exact loader exported from a different route.
Same concept for the action's part.
Asking this to know whether this would be safe both (because of some unknown to me internal logic of Remix) and future-proof.
Complete usage example
Beta Was this translation helpful? Give feedback.
All reactions