Skip to content

Instantly share code, notes, and snippets.

@mkarajohn
Last active February 9, 2024 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkarajohn/1309612398d81ce8f44acf711ba21e61 to your computer and use it in GitHub Desktop.
Save mkarajohn/1309612398d81ce8f44acf711ba21e61 to your computer and use it in GitHub Desktop.
Customizable specific react-query hook
// Usecase: Say you have an endpoint `/clients` and you have created a custom
// hook, that wraps over a `useQuery` that has a fixed `queryKey` and `queryFn`
// (because it is supposed to only fetch data from the `/clients` endpoint)
// However you want to be able to pass a valid `useQuery` config object in order
// to customize its behaviour (except for passing a custom queryKey or queryFn)
// This is one way to do this.
// 2023 Dimitris Karagiannis
// Twitter: @MitchKarajohn
export function useSpecificButCustomizableQuery(
queryOptions: Omit<
UseQueryOptions<
TypeOfReturnValue,
unknown,
TypeOfReturnValue,
TypeOfTheQueryKey
>,
'queryKey' | 'queryFn'
> = {}
) {
return useQuery<
TypeOfReturnValue,
unknown,
TypeOfReturnValue,
TypeOfTheQueryKey
>({
...queryOptions,
queryKey: ['your', 'key'],
queryFn: (): Promise<TypeOfReturnValue> => {}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment