Skip to content

Instantly share code, notes, and snippets.

@cosemansp
Created August 20, 2021 16:42
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 cosemansp/370b2dd7c047c98e16be520670c05e94 to your computer and use it in GitHub Desktop.
Save cosemansp/370b2dd7c047c98e16be520670c05e94 to your computer and use it in GitHub Desktop.
function createQueryFn(baseUrl: string): QueryFunction {
return async ({queryKey}) => {
const path =
typeof queryKey === 'string' ? queryKey : queryKey[0] + qs(queryKey[1])
const res = await fetch(baseUrl + path)
if (!res.ok) throw new Error(await res.json())
return res.json()
}
}
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: createQueryFn('https://api_base_url'),
},
},
})
// query with simple query key as string
export function useMovies() {
// a GET request will be fired to https://api_base_url/api/movies
return useQuery('/api/movies')
}
// OR
// query with complex query key as object
export function useMovies({page, pageSize, searchTerm}) {
// a GET request will be fired to
// https://api_base_url/api/movies?page=0&pageSize=10&searchTerm=matrix
return useQuery('/api/movies', {page, pageSize, searchTerm})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment