React Query
It's likely that you may need to use your server actions for querying data on the client side. In order to do this, we recommend using zsa
with @tanstack/react-query
(aka React Query).
IMPORTANT: Although it is available in the library, please be advised against using server actions to query data. Server actions are currently optimised for mutations. This may be deprecated in the future. Apologies for any confusion. For better results, you should create an API route and fetch data normally using a GET request.
React Query is the leading solution for asynchronous querying and state
management in React. By using React Query, you will have all the functionality
of React Query for using your zsa
server actions on the client side.
Installation
To get started, make sure you have installed zsa-react-query
and @tanstack/react-query
:
Next, wrap your application in a React Query provider:
Finally, set up your hooks at @/lib/hooks/server-action-hooks.ts
Using now you can utilize useServerActionQuery
, useServerActionMutation
, and useServerActionInfiniteQuery
for your server actions.
These hooks are synonymous with the useQuery
useMutation
and useInfiniteQuery
hooks from React Query, the only difference being the first argument of these hooks will be your desired server action, and the second argument being all the same options and inputs required in their corresponding React Query hook.
The return value of all zsa-react-query
hooks will be the same return value of their corresponding React Query hooks.
For further guidance on how to use these hooks, we recommend you look towards the React Query Docs for more information.
Usage
For a basic example of how to use zsa-react-query
, lets create a simple, queryable server action.
Querying from the client:
In the client component:
- Import
helloWorldAction
and theuseServerActionQuery
hook. - Call
useServerActionQuery
with the imported action and provide the necessary input and options. - Bind the user input to the server action's input using state and debounce it to avoid excessive requests.
- Render different views based on the
helloWorldAction
's state (isLoading
,isSuccess
,isError
).
Here is the result:
Say hello
This card refetches your server action as you type
As you can see, zsa
provides built-in error and loading states and allows easy integration of server actions into your client components.