Created
November 25, 2019 09:40
-
-
Save Pro542/81cd72778afca84361248466dc7bd54d to your computer and use it in GitHub Desktop.
Reusable react state hook to handle api calls
This file contains 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
/* | |
* Hook to reuse state logic for api calls | |
* | |
*/ | |
function useApiCall(api: AxiosInstance, params: any[], onError: any => any) { | |
const [data, setData] = useState(null); | |
const [isLoading, setIsLoading] = useState(false); | |
const [error, setError] = useState(null); | |
useEffect(async () => { | |
setIsLoading(true) | |
try { | |
const response = await api(...params); | |
setData(response.data); | |
} catch(e) { | |
onError(e); | |
} | |
setIsLoading(false) | |
}); | |
return [data, error, isLoading] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment