When using server actions to query data, you may need to explicitly refetch that data when it becomes stale. This can be achieved using the React QueryuseQueryClient hook.
For more insight on queryKeys and useQueryClient, we recommend looking
towards the React Query
Docs
In order to maintain typesafety while refetching data, we recommend placing a QueryKeyFactory in your @/lib/hooks/server-actions-hooks.ts. Here is an example
By doing this, your queryKeys in all your zsa-react-query hooks will now be typesafe.
Next, we will define a server action that fetches the data. In this example, we'll create an action that simply returns a random number:
This action takes a min and max value as input, validates that min is less than max, and returns a random number between those values after a simulated .5-second delay.
Next, use the useServerActionQuery hook to call the action in a client component:
The useServerActionQuery hook is called with the getRandomNumber action and an options object containing the input values and a queryKey. The component displays the random number returned by the action.
To manually refetch the data, use the useQueryClient hook in another component:
This component renders a button that, when clicked, calls the refetch function with the same queryKey used in the RandomNumberDisplay component. This will cause the server action to be re-executed and the data to be refreshed.
Random number
This fetches a random number upon mounting
Random number:
loading...
Refetch Button:
By using the useQueryClient hook in conjunction with a QueryKeyFactory, you can easily refetch data when needed in your application.
For more info on how queryKeys work, check out the React Query Docs