Created
April 30, 2021 10:56
-
-
Save ilxanlar/66c78967bcd06e10ebd4fa813f5aa24e 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 { 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