Skip to content

Instantly share code, notes, and snippets.

@mohammad-hassani
Last active April 12, 2022 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohammad-hassani/a2c6bcbca0804e1f80bfc3d839df3acf to your computer and use it in GitHub Desktop.
Save mohammad-hassani/a2c6bcbca0804e1f80bfc3d839df3acf to your computer and use it in GitHub Desktop.
This is an example of Fetch function in react-native that contains lots of parameters like: navigation, URL, method, urlParams, headers, base-URL, auth, etraURL, body and connection check
import NetInfo from '@react-native-community/netinfo';
import {NavigationProp, ParamListBase} from '@react-navigation/native';
interface FetchProps {
navigation: NavigationProp<ParamListBase>;
base?: string;
url: string;
method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'UPDATE' | 'DELETE';
body?: any;
headers?: {
'Content-Type': 'multipart/form-data' | 'application/json';
Authorization?: `Bearer ${string}`;
Accept?: 'application/json';
};
urlParams?: any;
auth?: string;
extraUrl?: string;
}
interface FetchOptionProp {
method: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'UPDATE' | 'DELETE';
headers?: {
'Content-Type': 'multipart/form-data' | 'application/json';
Authorization?: string;
Accept?: 'application/json';
};
body?: any;
}
const Fetch = async ({
navigation,
url,
method = 'GET',
body,
urlParams,
headers,
base = 'http://baseurl.example',
auth,
extraUrl,
}: FetchProps) => {
const options: FetchOptionProp = {
method: method,
headers: headers || {
'Content-Type': 'application/json',
Accept: 'application/json',
},
};
if (body) {
options.body = JSON.stringify(body);
}
if (auth) {
options.headers!.Authorization = 'Bearer ' + auth;
}
if (urlParams) {
url = url + `/${urlParams}`;
}
if (extraUrl) {
url = url + extraUrl;
}
const completeURL = base + url;
const state: any = await NetInfo.fetch();
if (state.isConnected) {
try {
const response: any = await fetch(completeURL, options);
if (response.status !== 200) {
console.info('status:', response.status);
console.info('url: ', completeURL);
console.info('error:', response);
} else {
return await response.json();
}
} catch (error) {
console.info(error);
}
} else {
console.log('no internet');
navigation.navigate('Offline');
}
};
export default Fetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment