Created
April 16, 2022 16:08
-
-
Save enzzoperez/050b3de8b50de634b7df4f1931be8f90 to your computer and use it in GitHub Desktop.
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, useEffect} from 'react'; | |
import axios, {AxiosError, AxiosRequestConfig} from 'axios'; | |
import Config from 'react-native-config'; //lib used for env vars | |
//set the base url for axios | |
axios.defaults.baseURL = Config.API_URL; | |
const useRemoteData = <T>({url, method, headers, data}: AxiosRequestConfig) => { | |
const [response, setResponse] = useState<T>(); | |
const [error, setError] = useState<AxiosError>(); | |
const [isLoading, setIsLoading] = useState(true); | |
useEffect(() => { | |
axios | |
.request({url, method, headers, data}) | |
.then(res => { | |
setResponse(res.data.data); | |
}) | |
.catch(err => { | |
setError(err); | |
}) | |
.finally(() => { | |
setIsLoading(false); | |
}); | |
}, [url, method, headers, data]); | |
return {response, error, isLoading}; | |
}; | |
export default useRemoteData; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment