Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

869493637 - add axios #23

Merged
merged 6 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API_URL=http://localhost:3000/
1 change: 0 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ module.exports = {
],
'react/react-in-jsx-scope': 'off',
'react-hooks/exhaustive-deps': 'warn',
indent: ['warn', 2, { SwitchCase: 1 }],
quotes: ['warn', 'single'],
semi: ['warn', 'always'],
},
Expand Down
1 change: 1 addition & 0 deletions App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createNativeStackNavigator } from '@react-navigation/native-stack';
import i18next from 'i18next';
import commonEN from 'public/locales/en/common.json';
import commonPL from 'public/locales/pl/common.json';
import React from 'react';
import { initReactI18next } from 'react-i18next';

import { ThemeProvider } from '@/hooks';
Expand Down
33 changes: 33 additions & 0 deletions api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { API_URL } from '@env';
import axios, { AxiosRequestConfig } from 'axios';

const api = axios.create({
baseURL: API_URL + '/api',
});

const get = <T extends object>(
url: string,
config: AxiosRequestConfig<any> | undefined = undefined,
): Promise<T> => api.get(url, config);

const del = <T extends object>(
url: string,
config: AxiosRequestConfig<any> | undefined = undefined,
): Promise<T> => api.delete(url, config);

const post = <T extends object>(
url: string,
data: unknown | undefined = undefined,
config: AxiosRequestConfig<any> | undefined = undefined,
): Promise<T> => api.post(url, data, config);

const put = <T extends object>(
url: string,
data: unknown | undefined = undefined,
config: AxiosRequestConfig<any> | undefined = undefined,
): Promise<T> => api.put(url, data, config);

const patch = <T extends object>(url: string, data: unknown): Promise<T> =>
api.patch(url, data);

export { get, del, post, put, patch };
12 changes: 12 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,21 @@ module.exports = function (api) {
'@': './src',
style: './style.ts',
public: './public',
api: './api',
},
},
],
[
'module:react-native-dotenv',
{
envName: 'APP_ENV',
moduleName: '@env',
path: '.env',
safe: false,
allowUndefined: true,
verbose: false,
},
],
],
};
};
3 changes: 3 additions & 0 deletions env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
declare module '@env' {
export const API_URL: string;
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@react-native/metro-config": "^0.73.3",
"@react-navigation/native": "^6.1.9",
"@react-navigation/native-stack": "^6.9.17",
"axios": "^1.6.8",
"expo": "~49.0.15",
"expo-status-bar": "~1.6.0",
"i18next": "^23.10.1",
Expand All @@ -23,6 +24,7 @@
"react-hook-form": "^7.48.2",
"react-i18next": "^14.1.0",
"react-native": "0.72.10",
"react-native-dotenv": "^3.4.11",
"react-native-safe-area-context": "4.6.3",
"react-native-screens": "~3.22.0",
"yarn": "^1.22.21",
Expand Down
Empty file removed src/controllers/.placeholder
Empty file.
4 changes: 4 additions & 0 deletions src/controllers/example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { get } from 'api';
import { AxiosResponse } from 'axios';

export const getExample = () => get<AxiosResponse<string>>('/');
1 change: 1 addition & 0 deletions src/controllers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './example';
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './useTheme';
export * from './usePromise';
55 changes: 55 additions & 0 deletions src/hooks/usePromise.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { AxiosError, AxiosResponse } from 'axios';
import { useState } from 'react';

const rethrow = (error: unknown): void => {
if (error instanceof AxiosError) {
if (error.response?.status === 500) {
throw new Error('There was unhandled server error');
}

if (error.response?.data?.message) {
const { message } = error.response.data;

if (typeof message === 'string') {
throw new Error(message);
}

if (typeof message === 'object') {
if (Array.isArray(message)) {
throw new Error(message.join(', '));
}

throw new Error(`Something went wrong: ${JSON.stringify(message)}`);
}
}
}

if (error instanceof Error) {
throw error;
}

throw new Error('Something went wrong');
};

export const usePromise = <T extends any>(
creator: () => Promise<AxiosResponse<T>>,
onSuccess: (data: AxiosResponse<T>) => void,
onFail: (err: Error) => void = rethrow,
): [invoker: () => void, isLoading: boolean] => {
const [isLoading, setIsloading] = useState(false);

const invoker = () => {
setIsloading(true);
creator()
.then((res) => {
setIsloading(false);
onSuccess(res);
})
.catch((reason) => {
setIsloading(false);
onFail(reason);
});
};

return [invoker, isLoading];
};
14 changes: 13 additions & 1 deletion src/screens/Components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ import { PrimaryButton } from '@/components/Button';
import { ConversationTile } from '@/components/ConversationTile';
import { TextInput } from '@/components/TextInput';
import { SwitchTheme } from '@/components/Theme';
import { getExample } from '@/controllers';
import { usePromise } from '@/hooks';
import { RootStackParamList } from '@/types/param';

type Props = NativeStackScreenProps<RootStackParamList, 'Components'>;

const Home = ({ navigation }: Props) => {
const { t } = useTranslation('common');

const [invoke, isLoading] = usePromise(getExample, (data) => {
console.log(data);
});

console.log(isLoading);

return (
<View style={styles.container}>
<Text>Components screen</Text>
Expand Down Expand Up @@ -53,7 +61,11 @@ const Home = ({ navigation }: Props) => {
lastMessage="lorem ipsum lorem ipsum lorem ipsum lorem ipsum. lorem ipsum"
lastMessageAuthor="Marek Kowalski"
/>
<PrimaryButton text="primary button" onPress={() => {}} />
<PrimaryButton
disabled={isLoading}
text="pobierz dane"
onPress={invoke}
/>
</View>
);
};
Expand Down
Loading
Loading