Skip to content

Instantly share code, notes, and snippets.

@Suaz
Created November 3, 2021 11:44
Show Gist options
  • Save Suaz/c5e0c1d66f3789e7ff42a0efb8a0fbcf to your computer and use it in GitHub Desktop.
Save Suaz/c5e0c1d66f3789e7ff42a0efb8a0fbcf to your computer and use it in GitHub Desktop.
hook to handle apiCalls
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