Data mutation
Edit this pageThis guide provides practical examples of using actions to mutate data in SolidStart.
Handling form submission
To handle <form>
submissions with an action:
- Ensure the action has a unique name. See the Action API reference for more information.
- Pass the action to the
<form>
element using theaction
prop. - Ensure the
<form>
element uses thepost
method for submission. - Use the
FormData
object in the action to extract field data using the naviteFormData
methods.
Passing additional arguments
To pass additional arguments to your action, use the with
method:
Showing pending UI
To display a pending UI during action execution:
- Import
useSubmission
from@solidjs/router
. - Call
useSubmission
with your action, and use the returnedpending
property to display pending UI.
Handling errors
To handle errors that occur within an action:
- Import
useSubmission
from@solidjs/router
. - Call
useSubmission
with your action, and use the returnederror
property to handle the error.
Validating form fields
To validate form fields in an action:
- Add validation logic in your action and return validation errors if the data is invalid.
- Import
useSubmission
from@solidjs/router
. - Call
useSubmission
with your action, and use the returnedresult
property to handle the errors.
Showing optimistic UI
To update the UI before the server responds:
- Import
useSubmission
from@solidjs/router
. - Call
useSubmission
with your action, and use the returnedpending
andinput
properties to display optimistic UI.
Multiple Submissions
If you want to display optimistic UI for multiple concurrent submissions, you can use the useSubmissions
primitive.
Redirecting
To redirect users to a different route within an action:
- Import
redirect
from@solidjs/router
. - Call
redirect
with the route you want to navigate to, and throw its response.
Using a database or an ORM
To safely interact with your database or ORM in an action, ensure it's server-only by adding "use server"
as the first line of your action:
Invoking an action programmatically
To programmatically invoke an action:
- Import
useAction
from@solidjs/router
. - Call
useAction
with your action, and use the returned function to invoke the action.