Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active August 28, 2020 23:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gragland/b00cbf50da72ef5c5d0eec9ec8a7922a to your computer and use it in GitHub Desktop.
Example for /u/caughtupstream299792
import React, { useState, useEffect, useCallback } from 'react';
// Hook
const useAsync = (asyncFunction, immediate = true) => {
const [status, setStatus] = useState('idle');
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
// The execute function wraps asyncFunction and
// handles setting state for pending, value, and error.
// useCallback ensures the below useEffect is not called
// on every render, but only if asyncFunction changes.
const execute = useCallback((...args) => {
setStatus('pending');
setValue(null);
setError(null);
return asyncFunction(...args)
.then(response => {
setValue(response);
setStatus('success');
})
.catch(error => {
setError(error);
setStatus('error');
});
}, [asyncFunction]);
// Call execute if we want to fire it right away.
// Otherwise execute can be called later, such as
// in an onClick handler.
useEffect(() => {
if (immediate) {
execute();
}
}, [execute, immediate]);
return { execute, status, value, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment