Skip to content

Instantly share code, notes, and snippets.

@enzzoperez
Created April 16, 2022 16:08
Show Gist options
  • Save enzzoperez/050b3de8b50de634b7df4f1931be8f90 to your computer and use it in GitHub Desktop.
Save enzzoperez/050b3de8b50de634b7df4f1931be8f90 to your computer and use it in GitHub Desktop.
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