Skip to content

Instantly share code, notes, and snippets.

@0xLDev
Created December 18, 2021 08:42
Show Gist options
  • Save 0xLDev/c341a329aaf922774746967744a14f76 to your computer and use it in GitHub Desktop.
Save 0xLDev/c341a329aaf922774746967744a14f76 to your computer and use it in GitHub Desktop.
import { useCallback, useState } from 'react';
export const ASYNC_STATUS = {
IDLE: 'idle',
PENDING: 'pending',
SUCCESS: 'success',
ERROR: 'error',
};
export const useAsync = (asyncFunc) => {
const [status, setStatus] = useState(ASYNC_STATUS.IDLE);
const [result, setResult] = useState();
const [error, setError] = useState();
const run = useCallback(() => {
if (status === ASYNC_STATUS.PENDING) {
console.error('Still pending, cannot run again...');
return;
}
setStatus(ASYNC_STATUS.PENDING);
asyncFunc()
.then((r) => {
setResult(r);
setError(null);
setStatus(ASYNC_STATUS.SUCCESS);
})
.catch((error) => {
setError(error);
setStatus(ASYNC_STATUS.ERROR);
});
}, [status, asyncFunc]);
return { run, status, result, error };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment