Created
November 3, 2021 11:44
-
-
Save Suaz/c5e0c1d66f3789e7ff42a0efb8a0fbcf to your computer and use it in GitHub Desktop.
hook to handle apiCalls
This file contains hidden or 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 } from 'react' | |
const useApi = (apiFunction: any) => { | |
const [data, setData] = useState() | |
const [error, setError] = useState(false) | |
const [loading, setLoading] = useState(false) | |
const request = async (...args: any[]) => { | |
try { | |
setLoading(true) | |
const response = await apiFunction(...args) | |
setData(response.data) | |
setError(false) | |
} catch (e) { | |
setError(true) | |
} finally { | |
setLoading(false) | |
} | |
} | |
return { data, loading, error, request } | |
} | |
export default useApi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment