Skip to content

Instantly share code, notes, and snippets.

@nwellis
Last active August 13, 2019 15:59
Show Gist options
  • Save nwellis/b3b75e3c2985b42fc8bc167f121a6478 to your computer and use it in GitHub Desktop.
Save nwellis/b3b75e3c2985b42fc8bc167f121a6478 to your computer and use it in GitHub Desktop.
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