Skip to content

Instantly share code, notes, and snippets.

@gomorizsolt
Last active June 4, 2019 15:05
Show Gist options
  • Save gomorizsolt/85e31485d1b138274299092ee6bfeb37 to your computer and use it in GitHub Desktop.
Save gomorizsolt/85e31485d1b138274299092ee6bfeb37 to your computer and use it in GitHub Desktop.
Generic fetch hook
import { useState, useEffect } from "react";
export const useGenericFetch = (fetchFunction, ...args) => {
const defaultState = {
data: null,
isLoading: true,
err: false
};
const [data, setData] = useState(defaultState);
useEffect(() => {
async function fetchData() {
try {
const fetchedData = await fetchFunction(...args);
setData({
...defaultState,
data: fetchedData,
isLoading: false,
err: false
});
} catch (e) {
setData({
...defaultState,
data: null,
isLoading: false,
err: true
});
}
}
fetchData();
}, []);
return data;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment