Skip to content

Instantly share code, notes, and snippets.

@rhefner
Last active March 27, 2020 23:33
Show Gist options
  • Save rhefner/bb7638d915d34bd6f35d51e23e8cd339 to your computer and use it in GitHub Desktop.
Save rhefner/bb7638d915d34bd6f35d51e23e8cd339 to your computer and use it in GitHub Desktop.
function usePromise(promise, args) {
const [results, setResults] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let isCurrent = true;
promise(...args)
.then((payload) => {
if (!isCurrent) return;
setResults(payload);
})
.catch((error) => {
if (!isCurrent) return;
setError(error);
});
return () => (isCurrent = false);
}, [promise, args]);
return { results, error };
}
function SomeProductComponent() {
const [getProductArgs, setGetProductArgs] = useState([1]);
const { results: product, error: productError } = usePromise(api.products.getProduct, getProductArgs);
if (productError) {
console.error('productError:', productError);
}
// Simulate an Error, which sets 'error'
useEffect(() => {
setTimeout(() => setGetProductArgs([`<productId that doesn't exist>`]), 2000);
}, []);
if (!product) return <div>Loading...</div>;
return <div>{JSON.stringify(product)}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment