Last active
March 27, 2020 23:33
-
-
Save rhefner/bb7638d915d34bd6f35d51e23e8cd339 to your computer and use it in GitHub Desktop.
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
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