Skip to content

Instantly share code, notes, and snippets.

@ilxanlar
Last active August 2, 2021 00:27
Show Gist options
  • Save ilxanlar/fbeafcd374e8ae833bd17ef6a18ae04e to your computer and use it in GitHub Desktop.
Save ilxanlar/fbeafcd374e8ae833bd17ef6a18ae04e to your computer and use it in GitHub Desktop.
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