Skip to content

Instantly share code, notes, and snippets.

@iskenxan
Last active August 28, 2021 01:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iskenxan/bfdda1300c9f001107fb7c548d79c5de to your computer and use it in GitHub Desktop.
Save iskenxan/bfdda1300c9f001107fb7c548d79c5de to your computer and use it in GitHub Desktop.
useAsync
export const useAsync = ({ asyncFunction }) => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [result, setResult] = useState(null);
const execute = useCallback(
async (...params) => {
try {
setLoading(true);
const response = await asyncFunction(...params);
setResult(response);
} catch (e) {
setError(e);
}
setLoading(false);
},
[asyncFunction]
);
return { error, result, loading, execute };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment