Last active
June 4, 2019 15:05
-
-
Save gomorizsolt/85e31485d1b138274299092ee6bfeb37 to your computer and use it in GitHub Desktop.
Generic fetch hook
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 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