Calling Directly
In addition to using the useServerAction
hook, you can also call server actions directly from your client components. This approach provides a simpler way to execute actions, but you won't have access to the built-in loading states, optimistic updates, and error handling provided by useServerAction
.
Usage
Executing the Action
To call a server action directly, you simply need to import the action and invoke it with the required input. Server actions return a promise that resolves to a tuple containing the result data and any error that occurred.
- If the action is successful,
data
will contain the returned data, anderr
will benull
. - If an error occurs during the execution of the action,
data
will benull
, anderr
will contain the error object.
You can handle the result of the action based on the presence of data
or err
.
When calling server actions directly, you are responsible for handling the asynchronous nature of the action and updating the component's state accordingly. You won't have access to the automatic loading states and error handling provided by useServerAction
.
Error Handling
If an error occurs during the execution of the server action, you can access the error object in the err
variable returned by the action. You can then update your component's state or display an error message to the user based on the error.
When handling errors directly, you have full control over how to present and manage the error state in your component.
Limitations
While calling server actions directly is a straightforward approach, it has some limitations compared to using the useServerAction
hook:
- You don't have access to the built-in loading states (
isPending
,isOptimistic
, etc.). - You need to manually handle the asynchronous nature of the action and update the component's state accordingly.
- You don't have the option to configure automatic retries or optimistic updates.
If you require more advanced functionality or a more declarative approach to managing server actions, consider using the useServerAction
hook instead.
That covers the basics of calling server actions directly in your client components. Remember to handle the asynchronous nature of the actions and manage the component's state appropriately.