Created
August 20, 2021 16:42
-
-
Save cosemansp/370b2dd7c047c98e16be520670c05e94 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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