DEV Community

Discussion on: React: Creating a Custom Hook for Fetching Data

Collapse
 
trangcongthanh profile image
Thành Trang • Edited

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()
...
}
Enter fullscreen mode Exit fullscreen mode

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

Fetch ex.:

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

I prefer return type same as React.useState api.

return [{ data, loading, error }, invoke]
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
admantium profile image
Sebastian

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.