My sugesstion:
The hook should take a promise as param. It will more flexible than take url
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.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
My sugesstion:
The hook should take a promise as param. It will more flexible than take
url
You can use fetch, axios, or any HTTP client library.
Fetch ex.:
I prefer return type same as React.useState api.
More easier for naming.
Alot of case, you will need more than 2 api calls. So you can:
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.