Skip to content
loading...

re: React: Creating a Custom Hook for Fetching Data VIEW POST

FULL DISCUSSION
 

My sugesstion:

The hook should take a promise as param. It will more flexible than take url

const useFetchData = (promiseFn) => {
...
const invoke = async () => {
...
const res = await promiseFn()
...
}

You can use fetch, axios, or any HTTP client library.

Fetch ex.:

const response = useFetchData(fetch('url', { method: 'POST' }).then(res => res.json))

I prefer return type same as React.useState api.

return [{ data, loading, error }, invoke]

More easier for naming.
Alot of case, you will need more than 2 api calls. So you can:

const [api1, api1InvokeFn] = useFetchData()
const [api2, api2InvokeFn] = useFetchData()

React.useEffect(() => {
// call api1 when mounted
api1InvokeFn()
}, [api1InvokeFn])

<button onClick={api2InvokeFn}>Fetch</button>

if (api1.loading) {
... show loading indicator
}
if (!api2.loading && api2.data) {
... do something data
}
 

Using promises improves the flexibilty of your app, in my case I'm happy to stay with the synchronous call and having a timeout barrier.

code of conduct - report abuse