Last active
August 13, 2019 15:59
-
-
Save nwellis/b3b75e3c2985b42fc8bc167f121a6478 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, useMemo, useCallback, useEffect } from 'react'; | |
const initialState = { | |
isLoading: false, | |
result: null, | |
error: null | |
}; | |
/** | |
* This could probably be done in a much better way. Seems really messy | |
*/ | |
export default function(initialCall, fetchInitially = false) { | |
const [resourceCall, updateCall] = useState(initialCall); | |
const [shouldFetch, setShouldFetch] = useState(fetchInitially); | |
const [resource, setResource] = useState({ ...initialState, isLoading: fetchInitially }); | |
const fetchData = useCallback(() => { | |
async function fetch() { | |
setShouldFetch(false); | |
setResource({ | |
isLoading: true, | |
result: null, | |
error: null | |
}); | |
try { | |
setResource({ | |
isLoading: false, | |
result: await resourceCall(), | |
error: null | |
}); | |
} catch (error) { | |
setResource({ | |
isLoading: false, | |
result: null, | |
error | |
}); | |
} | |
} | |
fetch(); | |
}, [resourceCall]); | |
useEffect(() => { | |
if (!shouldFetch) return; | |
fetchData(); | |
}, [shouldFetch, fetchData]); | |
return useMemo( | |
() => ({ | |
resource, | |
fetchData, | |
updateCall | |
}), | |
[resource, fetchData] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment