Skip to content

Instantly share code, notes, and snippets.

@ponyjackal
Last active November 16, 2020 10:39
Show Gist options
  • Save ponyjackal/57d25b66e1b204a892ab73274e085ad8 to your computer and use it in GitHub Desktop.
Save ponyjackal/57d25b66e1b204a892ab73274e085ad8 to your computer and use it in GitHub Desktop.
usePromise
import { useState, useEffect } from "react";
export const usePromise = (
fn,
{ resolve = false, resolveCondition = [] } = {}
) => {
const [data, setData] = useState();
const [isLoading, setLoading] = useState(resolve);
const [lastUpdated, setLastUpdated] = useState();
const [error, setError] = useState();
const request = async (...args) => {
setLoading(true);
try {
const result = await fn(...args);
setData(result);
setLastUpdated(Date.now());
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
if (resolve) {
useEffect(request, resolveCondition);
}
return {
request,
data,
isLoading,
lastUpdated,
error
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment