openapi-react-query-codegen icon indicating copy to clipboard operation
openapi-react-query-codegen copied to clipboard

Allow generation of simple query functions instead of hooks

Open bryanjtc opened this issue 1 year ago • 6 comments

Is your feature request related to a problem? Please describe. I cannot use a hook outside a component. This is not ideal when I use react router loaders.

Describe the solution you'd like

// Current query definition
export const useContactDetailsServiceGetContactDetails = ({ client }, queryKey?, options?) => 
  useQuery({ 
    queryKey: Common.UseContactDetailsServiceGetContactDetailsKeyFn({ client }, queryKey), 
    queryFn: () => ContactDetailsService.getContactDetails({ client }), ...options 
  });

// New query definition Option
export const UseContactDetailsSimpleServiceGetContactDetails = async (queryClient, { client }, queryKey?, options?) => 
  await queryClient.ensureQueryData({
    queryKey: Common.UseContactDetailsServiceGetContactDetailsKeyFn({ client }, queryKey),
    queryFn: () => ContactDetailsService.getContactDetails({ client }),
  })

// This will allow me to do this
export const loader =
  (queryClient) =>
  async ({ params }) => {
    return await UseContactDetailsSimpleServiceGetContactDetails(queryClient, { params.client })
  }

Adding a cli option to generate one type of query or both can be added.

Describe alternatives you've considered Manually creating the new query definition

Additional context Add any other context or screenshots about the feature request here.

bryanjtc avatar May 31 '24 16:05 bryanjtc

I like the idea of adding an option to pass the queryClient per request. If not provided, it defaults to a global singleton instance.

seriouslag avatar Jun 09 '24 17:06 seriouslag

can't this be done using prefetch? maybe exporting queryClient.fetchQuery? as well prefetch?

omridevk avatar Jun 12 '24 22:06 omridevk

Upon reading this again, I believe I missed your point.

We could generate the ensureQueryData function calls. Could you describe when you use them so we can build a realistic example?

seriouslag avatar Jun 14 '24 00:06 seriouslag

I use them in react router loaders. The function allows me to fetch the data before the route renders.

bryanjtc avatar Jun 15 '24 00:06 bryanjtc

I was also browsing this repo as a candidate codegen to use with tanstack router. Adding generated functions for ensureQueryData or just the queryOptions that can then be used with ensureQueryData, invalidateQueries, etc. would be immensely helpful.

Direct link to tanstack router docs example of what a basic use case looks like: https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#a-more-realistic-example-using-tanstack-query

Marsunpaisti avatar Aug 26 '24 09:08 Marsunpaisti

It seems these can be implemented similarly to the already existing prefetchQuery functionality.

7nohe avatar Sep 16 '24 08:09 7nohe