action
Edit this pageaction wraps an async function and returns an action function with router submission tracking. Matching submissions can be read with useSubmission and useSubmissions.
Import
import { action } from "@solidjs/router";Type
function action<T extends Array<any>, U = void>( fn: (...args: T) => Promise<U>, name?: string): Action<T, U>;
function action<T extends Array<any>, U = void>( fn: (...args: T) => Promise<U>, options?: { name?: string; onComplete?: (submission: Submission<T, U>) => void; }): Action<T, U>;Parameters
fn
- Type:
(...args: T) => Promise<U> - Required: Yes
Async function called when the action runs.
When native form handling calls the action, the argument is FormData for multipart/form-data forms and URLSearchParams otherwise.
options
- Type:
{ name?: string; onComplete?: (submission: Submission<T, U>) => void } - Required: No
Action options.
name
- Type:
string - Required: No
Name used to create the action URL when passing an options object.
onComplete
- Type:
(submission: Submission<T, U>) => void - Required: No
Function called after the action response is handled.
Return value
action returns a function with the following properties:
url
- Type:
string
String used when the action is rendered as a form action and when submissions are matched back to this action. The optional name provides a stable value for this string.
with
- Type:
(...args: any[]) => Action<any[], U>
Function that creates an action with leading arguments prefilled.
Behavior
- Calling an action adds a submission to the router submissions signal.
- Each submission exposes
input,url,result,error,pending,clear, andretry. withcreates another action that calls the original action with leading arguments already supplied.onCompletereceives a submission snapshot after the response is handled.Responseobjects with anX-Revalidateheader supply the keys passed torevalidate; without that header, action response handling passesundefined.- Returned
Responseobjects with aLocationheader trigger client navigation to that location. - On the client, actions are registered by URL in the action map and removed during cleanup when an owner exists.
- If an action has no URL, converting it to a string throws.
Examples
Basic usage
import { action } from "@solidjs/router";
const addTodo = action(async (data: URLSearchParams) => { return data.get("title")?.toString();}, "addTodo");
function TodoForm() { return ( <form action={addTodo} method="post"> <input name="title" /> <button>Add todo</button> </form> );}Prefilled arguments
import { action } from "@solidjs/router";
const addTodo = action(async (userId: string, data: URLSearchParams) => { return { userId, title: data.get("title")?.toString(), };}, "addTodo");
function TodoForm(props: { userId: string }) { return ( <form action={addTodo.with(props.userId)} method="post"> <input name="title" /> <button>Add todo</button> </form> );}