Created
September 4, 2021 10:21
-
-
Save dagi3d/c4c4242d5dacad1333c538cc00432249 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 { useState } from 'react'; | |
import api from '../api'; | |
function useApi() { | |
const requests = {}; | |
const proxy = new Proxy({}, { | |
get: (target, prop) => { | |
if (Object.prototype.hasOwnProperty.call(target, prop)) return target[prop]; | |
return async () => { | |
const response = await api[prop](); | |
requests[prop](response); | |
} | |
} | |
}); | |
const useRequest = function (method) { | |
const [state, setState] = useState(); | |
requests[method] = setState; | |
return [ | |
state, | |
] | |
}; | |
proxy.useRequest = useRequest; | |
return proxy; | |
} | |
export default useApi; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment