Last active
August 2, 2021 00:27
-
-
Save ilxanlar/fbeafcd374e8ae833bd17ef6a18ae04e to your computer and use it in GitHub Desktop.
This file contains 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
import { useQuery } from 'react-query' | |
import { stringify } from 'qs' | |
/* We could read this from some config or env */ | |
const API_ROOT = 'https://api.example.com' | |
/* A helper function to create URL from path and params */ | |
function getUrl(path, params) { | |
let url = API_ROOT + path | |
if (params && Object.keys(params).length > 0) { | |
url = url + '?' + stringify(params) | |
} | |
return url | |
} | |
/* A custom hook that utilizes ReactQuery's useQuery hook | |
* @query: A function that return standard query object | |
*/ | |
export default function useMyQuery(query, options) { | |
const { variables, ...reactQueryOptions } = options | |
const { name, path, params } = query(variables) | |
const queryKey = [name, path, params] | |
const queryFn = () => fetch(getUrl(path, params)).then(res => res.json()) | |
return useQuery(queryKey, queryFn, { | |
...reactQueryOptions | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment