useSubmission
Edit this pageThe useSubmission
function returns a submission object for a specified action.
This submission object contains properties to access the state of action execution and functions to control the action.
import { Show } from "solid-js";import { action, useSubmission } from "@solidjs/router";
const addTodoAction = action(async (formData: FormData) => { const name = formData.get("name")?.toString() ?? ""; if (name.length <= 2) { throw new Error("Name must be larger than 2 characters"); }}, "addTodo");
function AddTodoForm() { const submission = useSubmission(addTodoAction); return ( <form action={addTodoAction} method="post"> <input name="name" /> <button type="submit">{submission.pending ? "Adding..." : "Add"}</button> <Show when={submission.error}> {(error) => ( <div> <p>{error().message}</p> <button onClick={() => submission.clear()}>Clear</button> <button onClick={() => submission.retry()}>Retry</button> </div> )} </Show> </form> );}
If an action is executed multiple times, the last submission will be returned.
To access all submissions, useSubmissions
[/solid-router/reference/data-apis/use-submissions] can be used.
Filter function
Optionally, useSubmission
accepts a second parameter, which is a filter function.
This function is executed for each submission and returns the first submission that passes through the filter.
The filter function takes the submitted data as its parameter and should return true
to select the submission and false
otherwise.
import { useSubmission } from "@solidjs/router";import { addTodoAction } from "./actions";
function LatestTodo() { const latestValidSubmission = useSubmission( addTodoAction, ([formData]: [FormData]) => { const name = formData.get("name")?.toString() ?? ""; return name.length > 2; } ); return <p>Latest valid submittion: {latestValidSubmission.result}</p>;}
Parameters
- action: The action for which you want to return submissions.
- filter (Optional): The filter function that receives the submitted data as its parameter.
It should return
true
if the submission passes the filter andfalse
otherwise.
Returns
useSubmission
returns an object containing the following properties:
- input: The input data of the action.
- result: The returned value of the action.
- error: Any error thrown from the action.
- pending: A boolean indicating whether the action is currently being executed.
- clear: A function to clear the results of the submission.
- retry: A function to re-execute the action.