Skip to content

Instantly share code, notes, and snippets.

@dagi3d
Created September 4, 2021 10:21
Show Gist options
  • Save dagi3d/c4c4242d5dacad1333c538cc00432249 to your computer and use it in GitHub Desktop.
Save dagi3d/c4c4242d5dacad1333c538cc00432249 to your computer and use it in GitHub Desktop.
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