useServerAction
useServerAction is a custom React hook provided by ZSA that allows you to easily execute server actions from your client components. It handles the execution, transition, loading states, optimistic updates, and error handling for you.
Basic Example
useServerActionallows you to use this server action from within your client components.executeexecutes the server action endpoint with the typesafe input directly fromonClick.
useServerAction uses the useTransition hook internally to handle the transition state of the action
Here is the result:
Increment Number
Count:
Usage
Parameters
serverAction: A server action created usingcreateServerAction.opts(optional): An object containing additional options:onError: A callback function to be called when the server action encounters an error. It receives an object with theerrproperty containing the error.onSuccess: A callback function to be called when the server action succeeds. It receives an object with thedataproperty containing the returned data.onStart: A callback function to be called when the server action starts executing.onFinish: A callback function to be called when the server action finishes executing, regardless of the outcome.initialData: Initial data to be used as thedatavalue before the server action is executed.retry: An object specifying the retry behavior:maxAttempts: The maximum number of retry attempts.delay: The delay in milliseconds between retry attempts, or a function that takes the current attempt number and error, and returns the delay.
persistErrorWhilePending: When you want to persist the error state while the server action is pending. Default isfalse.persistDataWhilePending: When you want to persist the data state while the server action is pending. Default isfalse. This is helpful if you have form fields that you want to keep filled even when there is an error on other fields.
Return Value
useServerAction returns an object with the following properties:
data: The data returned by the server action, orundefinedif the action hasn't completed successfully yet.isPending: A boolean indicating whether the server action is currently being executed.isOptimistic: A boolean indicating whether thedatais an optimistic update.isError: A boolean indicating whether the server action encountered an error.error: The error object if the server action encountered an error, orundefinedotherwise.isSuccess: A boolean indicating whether the server action completed successfully.status: The current status of the server action:"idle","pending","success", or"error".execute: A function to execute the server action with the provided input.setOptimistic: A function to set an optimistic update for thedatavalue. It accepts either the new data directly or a function that receives the current data and returns the new data.reset: A function to reset the state of the server action to its initial values.
Retry Behavior
useServerAction supports automatic retries when the server action encounters an error. You can configure the retry behavior using the retry option:
maxAttempts: Specifies the maximum number of retry attempts. Default is no retries.delay: Specifies the delay in milliseconds between retry attempts. It can be a fixed number or a function that takes the current attempt number and error, and returns the delay. Default is no delay.
The retry option is useful for handling temporary network issues or server errors that may resolve after a short delay.
Optimistic Updates
useServerAction allows you to set optimistic updates for the data value using the setOptimistic function. Optimistic updates let you update the UI immediately based on the expected outcome of the server action, providing a better user experience.
You can pass either the new data directly or a function that receives the current data and returns the new data to setOptimistic. If the server action fails, the optimistic update will be rolled back to the previous value.
Form Actions
useServerAction also supports executing a form action directly. This is useful when you want to handle form submissions in your React components.
To do this, you can use the executeFormAction function passed back by useServerAction hook.
First, make sure you have the input type set to "formData" in your server action.
Then, you can use the executeFormAction function to execute the form action.
Here is the result:
Form Example
That's it! You can now use useServerAction to execute server actions and handle their results in your React components with ease.