Last active
November 16, 2020 10:39
-
-
Save ponyjackal/57d25b66e1b204a892ab73274e085ad8 to your computer and use it in GitHub Desktop.
usePromise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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