Skip to content

Instantly share code, notes, and snippets.

@ilxanlar
Created April 30, 2021 10:56
Show Gist options
  • Save ilxanlar/66c78967bcd06e10ebd4fa813f5aa24e to your computer and use it in GitHub Desktop.
Save ilxanlar/66c78967bcd06e10ebd4fa813f5aa24e to your computer and use it in GitHub Desktop.
import { useCallback } from 'react'
import { useMutation } 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) {
return API_ROOT + path
}
/* A custom hook that utilizes ReactQuery's useMutation hook */
export default function useMyMutation(mutation, options) {
const mutationFn = useCallback(
(variables = {}) => {
const { method, path, params } = mutation(variables)
const fetchOptions = {
body: params ? JSON.stringify(params) : undefined,
method: method || 'POST'
}
return fetch(getUrl(path), fetchOptions).then(res => res.json())
},
[mutation]
)
return useMutation(mutationFn, options)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment