@umang-thakkar/base-template 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -282
- package/package.json +11 -2
- package/template/.eslintrc +16 -46
- package/template/.prettierrc.js +8 -0
- package/template/App.tsx +11 -15
- package/template/Main.tsx +29 -5
- package/template/__mocks__/react-native-mmkv.ts +59 -0
- package/template/__tests__/App.test.tsx +6 -1
- package/template/__tests__/helpers.test.ts +43 -0
- package/template/babel.config.js +2 -1
- package/template/constants/API_Routes.ts +19 -0
- package/template/constants/AppConstants.tsx +1 -1
- package/template/constants/AppString.ts +36 -0
- package/template/constants/StoragePreferences.ts +120 -57
- package/template/jest.config.js +5 -0
- package/template/jest.setup.js +5 -0
- package/template/package.json +4 -4
- package/template/src/api/AxiosActions.ts +65 -28
- package/template/src/api/AxiosClient.ts +13 -7
- package/template/src/api/queries.ts +59 -29
- package/template/src/api/service.ts +23 -9
- package/template/src/components/ErrorBoundary.tsx +27 -31
- package/template/src/components/SnackbarHost.tsx +86 -0
- package/template/src/helper/colors.ts +22 -22
- package/template/src/helper/common-functions.ts +56 -10
- package/template/src/helper/matrics.ts +30 -0
- package/template/src/helper/navigation-service.ts +21 -24
- package/template/src/helper/snackbar.ts +41 -0
- package/template/src/helper/typography.ts +2 -2
- package/template/src/helper/utility-functions.ts +41 -69
- package/template/src/hooks/ThemeContext.tsx +60 -30
- package/template/src/hooks/usePaginatedAPI.ts +96 -0
- package/template/src/navigation/AppStack.tsx +36 -27
- package/template/src/navigation/screens.ts +17 -11
- package/template/src/redux/slice.ts +17 -12
- package/template/src/redux/slices/authSlice.ts +11 -14
- package/template/src/redux/store.ts +14 -10
- package/template/src/redux/types.d.ts +40 -19
- package/template/src/screens/HomeScreen.tsx +103 -29
- package/template/src/screens/LoginScreen.tsx +101 -69
- package/template/src/screens/SplashScreen.tsx +36 -25
- package/template/src/theme/darkTheme.ts +13 -6
- package/template/src/theme/index.ts +4 -3
- package/template/src/theme/lightTheme.ts +13 -5
- package/template/ios/.xcode.env.local +0 -1
package/template/babel.config.js
CHANGED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every backend endpoint, in one place. Service functions in
|
|
3
|
+
* src/api/service.ts build URLs from these; screens never hard-code paths.
|
|
4
|
+
*
|
|
5
|
+
* Group by feature. For routes with an id, store the base path and append
|
|
6
|
+
* the id in the service function: `${API_Routes.todos}/${id}`.
|
|
7
|
+
*/
|
|
8
|
+
export const API_Routes = {
|
|
9
|
+
// Auth
|
|
10
|
+
login: '/auth/login',
|
|
11
|
+
register: '/auth/register',
|
|
12
|
+
refreshToken: '/auth/refresh',
|
|
13
|
+
|
|
14
|
+
// Todos (demo endpoints on jsonplaceholder.typicode.com)
|
|
15
|
+
todos: '/todos',
|
|
16
|
+
|
|
17
|
+
// Files
|
|
18
|
+
uploadFile: '/files',
|
|
19
|
+
} as const;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const API_BASE_URL = 'https://jsonplaceholder.typicode.com';
|
|
1
|
+
export const API_BASE_URL = 'https://jsonplaceholder.typicode.com';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* All user-facing text. Screens and components read strings from here
|
|
3
|
+
* instead of hard-coding them. (Multi-language apps: move these into
|
|
4
|
+
* locales/*.json with i18next and keep the same keys.)
|
|
5
|
+
*/
|
|
6
|
+
export const AppString = {
|
|
7
|
+
// Auth
|
|
8
|
+
welcomeBack: 'Welcome back',
|
|
9
|
+
signInToContinue: 'Sign in to continue',
|
|
10
|
+
login: 'Sign in',
|
|
11
|
+
logout: 'Log out',
|
|
12
|
+
email: 'Email',
|
|
13
|
+
enterEmail: 'Enter your email',
|
|
14
|
+
password: 'Password',
|
|
15
|
+
enterPassword: 'Enter your password',
|
|
16
|
+
show: 'Show',
|
|
17
|
+
hide: 'Hide',
|
|
18
|
+
|
|
19
|
+
// Home
|
|
20
|
+
hello: 'Hello',
|
|
21
|
+
currentTheme: 'Current theme',
|
|
22
|
+
toggleTheme: 'Toggle theme',
|
|
23
|
+
followSystem: 'Follow system',
|
|
24
|
+
|
|
25
|
+
// Validation
|
|
26
|
+
emailRequired: 'Email is required',
|
|
27
|
+
invalidEmail: 'Enter a valid email',
|
|
28
|
+
passwordRequired: 'Password is required',
|
|
29
|
+
passwordMin: 'Password must be at least 6 characters',
|
|
30
|
+
|
|
31
|
+
// Common
|
|
32
|
+
loading: 'Loading…',
|
|
33
|
+
noDataFound: 'No data found',
|
|
34
|
+
somethingWentWrong: 'Something went wrong. Please try again.',
|
|
35
|
+
loginSuccess: 'Signed in successfully',
|
|
36
|
+
} as const;
|
|
@@ -1,94 +1,157 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { createMMKV } from 'react-native-mmkv';
|
|
2
|
+
import type { Storage } from 'redux-persist';
|
|
3
|
+
|
|
4
|
+
/** MMKV storage instance (react-native-mmkv v4). */
|
|
5
|
+
export const storage = createMMKV();
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Predefined storage keys used across the application.
|
|
9
|
+
*/
|
|
10
|
+
export const StorageKeys = {
|
|
11
|
+
AUTH_TOKEN: 'auth_token',
|
|
12
|
+
USER_DATA: 'user_data',
|
|
13
|
+
THEME_MODE: 'theme_mode',
|
|
14
|
+
LANGUAGE: 'language',
|
|
15
|
+
IS_FIRST_TIME: 'is_first_time',
|
|
16
|
+
} as const;
|
|
17
|
+
|
|
18
|
+
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys] | string;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Redux-persist compatible storage engine backed by MMKV.
|
|
22
|
+
* Adapts MMKV's synchronous API to the Promise-based interface expected by redux-persist.
|
|
23
|
+
*/
|
|
24
|
+
export const reduxStorage: Storage = {
|
|
25
|
+
setItem: (key: string, value: string): Promise<boolean> => {
|
|
26
|
+
storage.set(key, value);
|
|
27
|
+
return Promise.resolve(true);
|
|
28
|
+
},
|
|
29
|
+
getItem: (key: string): Promise<string | null> => {
|
|
30
|
+
const value = storage.getString(key);
|
|
31
|
+
return Promise.resolve(value ?? null);
|
|
32
|
+
},
|
|
33
|
+
removeItem: (key: string): Promise<void> => {
|
|
34
|
+
storage.remove(key);
|
|
35
|
+
return Promise.resolve();
|
|
36
|
+
},
|
|
37
|
+
};
|
|
2
38
|
|
|
3
39
|
/**
|
|
4
|
-
* Retrieves data from
|
|
40
|
+
* Retrieves data from MMKV with optional JSON parsing (Synchronous).
|
|
5
41
|
* @param key - The key of the item to retrieve.
|
|
6
42
|
* @param parseJSON - Whether to parse the value as JSON (default: false).
|
|
7
43
|
* @returns The stored value or null if not found.
|
|
8
44
|
*/
|
|
9
|
-
export const getData =
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
): Promise<T | null> => {
|
|
13
|
-
try {
|
|
14
|
-
const value = await AsyncStorage.getItem(key);
|
|
15
|
-
|
|
16
|
-
if (value === null) return null;
|
|
45
|
+
export const getData = <T = string>(key: string, parseJSON: boolean = false): T | null => {
|
|
46
|
+
try {
|
|
47
|
+
const value = storage.getString(key);
|
|
17
48
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
} catch (parseError) {
|
|
22
|
-
console.warn(`Failed to parse JSON for key "${key}":`, parseError);
|
|
23
|
-
return value as T;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
49
|
+
if (value === undefined || value === null) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
26
52
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
53
|
+
if (parseJSON) {
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(value) as T;
|
|
56
|
+
} catch (parseError) {
|
|
57
|
+
console.warn(`Failed to parse JSON for key "${key}":`, parseError);
|
|
58
|
+
return value as unknown as T;
|
|
59
|
+
}
|
|
31
60
|
}
|
|
61
|
+
|
|
62
|
+
return value as unknown as T;
|
|
63
|
+
} catch (error) {
|
|
64
|
+
console.error(`Error retrieving data for key "${key}":`, error);
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
32
67
|
};
|
|
33
68
|
|
|
34
69
|
/**
|
|
35
|
-
* Stores data in
|
|
70
|
+
* Stores data in MMKV with automatic JSON stringification for objects/arrays (Synchronous).
|
|
36
71
|
* @param key - The key to store the item under.
|
|
37
72
|
* @param value - The value to store.
|
|
38
73
|
* @returns True if successful, false otherwise.
|
|
39
74
|
*/
|
|
40
|
-
export const setData =
|
|
75
|
+
export const setData = <T>(key: string, value: T): boolean => {
|
|
41
76
|
try {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
77
|
+
if (typeof value === 'string') {
|
|
78
|
+
storage.set(key, value);
|
|
79
|
+
} else if (typeof value === 'number') {
|
|
80
|
+
storage.set(key, value);
|
|
81
|
+
} else if (typeof value === 'boolean') {
|
|
82
|
+
storage.set(key, value);
|
|
83
|
+
} else {
|
|
84
|
+
storage.set(key, JSON.stringify(value));
|
|
85
|
+
}
|
|
45
86
|
return true;
|
|
46
87
|
} catch (error) {
|
|
47
|
-
|
|
88
|
+
console.error(`Error storing data for key "${key}":`, error);
|
|
48
89
|
return false;
|
|
49
90
|
}
|
|
50
91
|
};
|
|
51
92
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Removes a single item from MMKV (Synchronous).
|
|
95
|
+
* @param key - The key of the item to remove.
|
|
96
|
+
* @returns True if successful, false otherwise.
|
|
97
|
+
*/
|
|
98
|
+
export const removeData = (key: string): boolean => {
|
|
58
99
|
try {
|
|
59
|
-
|
|
60
|
-
|
|
100
|
+
storage.remove(key);
|
|
101
|
+
return true;
|
|
61
102
|
} catch (error) {
|
|
62
|
-
|
|
63
|
-
|
|
103
|
+
console.error(`Error removing data for key "${key}":`, error);
|
|
104
|
+
return false;
|
|
64
105
|
}
|
|
65
106
|
};
|
|
66
107
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
108
|
+
/**
|
|
109
|
+
* Clears all data from MMKV (Synchronous).
|
|
110
|
+
* @returns True if successful, false otherwise.
|
|
111
|
+
*/
|
|
112
|
+
export const removeAll = (): boolean => {
|
|
72
113
|
try {
|
|
73
|
-
|
|
74
|
-
|
|
114
|
+
storage.clearAll();
|
|
115
|
+
return true;
|
|
75
116
|
} catch (error) {
|
|
76
|
-
|
|
77
|
-
|
|
117
|
+
console.error('Error clearing all storage:', error);
|
|
118
|
+
return false;
|
|
78
119
|
}
|
|
79
120
|
};
|
|
80
121
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
122
|
+
/**
|
|
123
|
+
* Checks if a key exists in MMKV (Synchronous).
|
|
124
|
+
* @param key - The key to check.
|
|
125
|
+
* @returns True if key exists, false otherwise.
|
|
126
|
+
*/
|
|
127
|
+
export const hasKey = (key: string): boolean => {
|
|
87
128
|
try {
|
|
88
|
-
|
|
89
|
-
return value !== null;
|
|
129
|
+
return storage.contains(key);
|
|
90
130
|
} catch (error) {
|
|
91
|
-
|
|
92
|
-
|
|
131
|
+
console.error(`Error checking key "${key}":`, error);
|
|
132
|
+
return false;
|
|
93
133
|
}
|
|
94
134
|
};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Helper object providing convenient type-safe access to MMKV.
|
|
138
|
+
*/
|
|
139
|
+
export const StoragePreferences = {
|
|
140
|
+
storage,
|
|
141
|
+
reduxStorage,
|
|
142
|
+
keys: StorageKeys,
|
|
143
|
+
get: getData,
|
|
144
|
+
set: setData,
|
|
145
|
+
getString: (key: string): string | undefined => storage.getString(key),
|
|
146
|
+
setString: (key: string, value: string): void => storage.set(key, value),
|
|
147
|
+
getNumber: (key: string): number | undefined => storage.getNumber(key),
|
|
148
|
+
setNumber: (key: string, value: number): void => storage.set(key, value),
|
|
149
|
+
getBoolean: (key: string): boolean | undefined => storage.getBoolean(key),
|
|
150
|
+
setBoolean: (key: string, value: boolean): void => storage.set(key, value),
|
|
151
|
+
remove: removeData,
|
|
152
|
+
removeAll,
|
|
153
|
+
hasKey,
|
|
154
|
+
getAllKeys: (): string[] => storage.getAllKeys(),
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
export default StoragePreferences;
|
package/template/jest.config.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
module.exports = {
|
|
2
2
|
preset: 'react-native',
|
|
3
|
+
// Packages shipped as untranspiled ESM/JSX that Jest must run through Babel.
|
|
4
|
+
transformIgnorePatterns: [
|
|
5
|
+
'node_modules/(?!((jest-)?react-native(-[a-z-]+)?|@react-native(-community)?|@react-navigation|react-redux|redux-persist|@reduxjs/toolkit|immer|@tanstack)/)',
|
|
6
|
+
],
|
|
7
|
+
setupFiles: ['react-native-gesture-handler/jestSetup', '<rootDir>/jest.setup.js'],
|
|
3
8
|
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/* global jest */
|
|
2
|
+
// Reanimated and Worklets need native modules; swap them for their official
|
|
3
|
+
// JS mocks so components that animate (SnackbarHost ...) render in Jest.
|
|
4
|
+
jest.mock('react-native-worklets', () => require('react-native-worklets/src/mock'));
|
|
5
|
+
jest.mock('react-native-reanimated', () => require('react-native-reanimated/mock'));
|
package/template/package.json
CHANGED
|
@@ -10,10 +10,8 @@
|
|
|
10
10
|
"test": "jest"
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@react-native-async-storage/async-storage": "^3.1.1",
|
|
14
13
|
"@react-navigation/native": "^7.3.3",
|
|
15
14
|
"@react-navigation/native-stack": "^7.17.5",
|
|
16
|
-
"@react-navigation/stack": "^7.10.5",
|
|
17
15
|
"@reduxjs/toolkit": "^2.12.0",
|
|
18
16
|
"@tanstack/react-query": "^5.101.0",
|
|
19
17
|
"axios": "^1.18.0",
|
|
@@ -21,11 +19,13 @@
|
|
|
21
19
|
"react": "19.2.3",
|
|
22
20
|
"react-native": "0.84.0",
|
|
23
21
|
"react-native-gesture-handler": "^3.0.1",
|
|
22
|
+
"react-native-mmkv": "^4.3.2",
|
|
23
|
+
"react-native-nitro-modules": "^0.35.0",
|
|
24
|
+
"react-native-reanimated": "~4.5.5",
|
|
24
25
|
"react-native-safe-area-context": "^5.8.0",
|
|
25
26
|
"react-native-screens": "^4.25.0",
|
|
26
27
|
"react-native-svg": "^15.12.1",
|
|
27
|
-
"react-native-
|
|
28
|
-
"react-native-worklets": "^0.10.0",
|
|
28
|
+
"react-native-worklets": "~0.10.4",
|
|
29
29
|
"react-redux": "^9.3.0",
|
|
30
30
|
"redux-persist": "^6.0.0"
|
|
31
31
|
},
|
|
@@ -1,37 +1,74 @@
|
|
|
1
|
+
import type { AxiosRequestConfig } from 'axios';
|
|
1
2
|
import { axiosClient } from './AxiosClient';
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Thin wrappers around the axios client. They return `response.data` and
|
|
6
|
+
* reject with the server's error body when there is one (so `err.message`
|
|
7
|
+
* is the backend's message), otherwise with the axios error.
|
|
8
|
+
*/
|
|
9
|
+
const unwrapError = (err: unknown) => {
|
|
10
|
+
const responseData = (err as { response?: { data?: unknown } })?.response?.data;
|
|
11
|
+
return responseData ?? err;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export async function getAPI<T = unknown>(url: string, params?: object): Promise<T> {
|
|
15
|
+
try {
|
|
16
|
+
const result = await axiosClient.get<T>(url, { params });
|
|
17
|
+
return result.data;
|
|
18
|
+
} catch (err) {
|
|
19
|
+
throw unwrapError(err);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function postAPI<T = unknown>(url: string, payload?: unknown): Promise<T> {
|
|
24
|
+
try {
|
|
25
|
+
const result = await axiosClient.post<T>(url, payload);
|
|
26
|
+
return result.data;
|
|
27
|
+
} catch (err) {
|
|
28
|
+
throw unwrapError(err);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function putAPI<T = unknown>(url: string, payload?: unknown): Promise<T> {
|
|
33
|
+
try {
|
|
34
|
+
const result = await axiosClient.put<T>(url, payload);
|
|
35
|
+
return result.data;
|
|
36
|
+
} catch (err) {
|
|
37
|
+
throw unwrapError(err);
|
|
38
|
+
}
|
|
10
39
|
}
|
|
11
40
|
|
|
12
|
-
export async function
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
41
|
+
export async function patchAPI<T = unknown>(url: string, payload?: unknown): Promise<T> {
|
|
42
|
+
try {
|
|
43
|
+
const result = await axiosClient.patch<T>(url, payload);
|
|
44
|
+
return result.data;
|
|
45
|
+
} catch (err) {
|
|
46
|
+
throw unwrapError(err);
|
|
47
|
+
}
|
|
19
48
|
}
|
|
20
49
|
|
|
21
|
-
export async function deleteAPI(url: string, params?:
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
50
|
+
export async function deleteAPI<T = unknown>(url: string, params?: object): Promise<T> {
|
|
51
|
+
try {
|
|
52
|
+
const result = await axiosClient.delete<T>(url, { params });
|
|
53
|
+
return result.data;
|
|
54
|
+
} catch (err) {
|
|
55
|
+
throw unwrapError(err);
|
|
56
|
+
}
|
|
28
57
|
}
|
|
29
58
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
59
|
+
/** Multipart upload. Build the body with `new FormData()` and `append(...)`. */
|
|
60
|
+
export async function uploadAPI<T = unknown>(
|
|
61
|
+
url: string,
|
|
62
|
+
body: FormData,
|
|
63
|
+
config?: AxiosRequestConfig,
|
|
64
|
+
): Promise<T> {
|
|
65
|
+
try {
|
|
66
|
+
const result = await axiosClient.post<T>(url, body, {
|
|
67
|
+
...config,
|
|
68
|
+
headers: { 'Content-Type': 'multipart/form-data', ...config?.headers },
|
|
69
|
+
});
|
|
70
|
+
return result.data;
|
|
71
|
+
} catch (err) {
|
|
72
|
+
throw unwrapError(err);
|
|
73
|
+
}
|
|
37
74
|
}
|
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
import axios from 'axios';
|
|
2
2
|
import { API_BASE_URL } from '../../constants/AppConstants';
|
|
3
|
+
import store from '../redux/store';
|
|
3
4
|
|
|
4
5
|
export const axiosClient = axios.create({
|
|
5
6
|
baseURL: API_BASE_URL,
|
|
6
|
-
timeout: 60000
|
|
7
|
+
timeout: 60000,
|
|
7
8
|
});
|
|
8
9
|
|
|
10
|
+
// Adds the access token from the auth slice to every request.
|
|
9
11
|
axiosClient.interceptors.request.use(
|
|
10
|
-
|
|
11
|
-
|
|
12
|
+
config => {
|
|
13
|
+
const token = store.getState().auth.accessToken;
|
|
14
|
+
if (token) {
|
|
15
|
+
config.headers.Authorization = `Bearer ${token}`;
|
|
16
|
+
}
|
|
12
17
|
return config;
|
|
13
18
|
},
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
19
|
+
error => Promise.reject(error),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
// Add a response interceptor here for token refresh / global 401 handling,
|
|
23
|
+
// e.g. dispatch(clearAuth()) and navigateAndSimpleReset('LoginScreen').
|
|
@@ -1,38 +1,68 @@
|
|
|
1
|
-
import { useMutation, useQuery, useQueryClient } from
|
|
2
|
-
import {
|
|
1
|
+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
2
|
+
import {
|
|
3
|
+
doAddTodo,
|
|
4
|
+
doDeleteTodo,
|
|
5
|
+
doGetTodoById,
|
|
6
|
+
doGetTodos,
|
|
7
|
+
doLogin,
|
|
8
|
+
doUpdateTodo,
|
|
9
|
+
} from './service';
|
|
10
|
+
import { usePaginatedAPI } from '../hooks/usePaginatedAPI';
|
|
11
|
+
import type { TodoItem } from '../redux/types';
|
|
3
12
|
|
|
13
|
+
/**
|
|
14
|
+
* SINGLE FILE for every React Query hook in the app.
|
|
15
|
+
* - Cache invalidation goes here (in the mutation's onSuccess).
|
|
16
|
+
* - UI reactions (snackbar, navigation) go in the screen's
|
|
17
|
+
* `mutate(vars, { onSuccess, onError })`.
|
|
18
|
+
*/
|
|
4
19
|
|
|
5
|
-
|
|
6
|
-
return useQuery({
|
|
7
|
-
queryKey: ['todos'],
|
|
8
|
-
queryFn: fetchTodos
|
|
9
|
-
});
|
|
10
|
-
};
|
|
20
|
+
// ---------- Auth ----------
|
|
11
21
|
|
|
12
|
-
export const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
22
|
+
export const useLogin = () => useMutation({ mutationFn: doLogin });
|
|
23
|
+
|
|
24
|
+
// ---------- Todos (demo) ----------
|
|
25
|
+
|
|
26
|
+
export const useTodoList = () =>
|
|
27
|
+
usePaginatedAPI({
|
|
28
|
+
queryKey: ['todos'],
|
|
29
|
+
queryFn: ({ pageParam, limit, search }) =>
|
|
30
|
+
doGetTodos({ _page: pageParam, _limit: limit, q: search || undefined }),
|
|
31
|
+
select: (pages: TodoItem[][]) => pages.flat(),
|
|
32
|
+
limit: 20,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
export const useTodoById = (id: number) =>
|
|
36
|
+
useQuery({
|
|
37
|
+
queryKey: ['todo', id],
|
|
38
|
+
queryFn: () => doGetTodoById(id),
|
|
39
|
+
enabled: !!id,
|
|
40
|
+
});
|
|
18
41
|
|
|
19
42
|
export const useAddTodo = () => {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
26
|
-
});
|
|
43
|
+
const queryClient = useQueryClient();
|
|
44
|
+
return useMutation({
|
|
45
|
+
mutationFn: doAddTodo,
|
|
46
|
+
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
47
|
+
});
|
|
27
48
|
};
|
|
28
49
|
|
|
29
|
-
export const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
50
|
+
export const useUpdateTodo = () => {
|
|
51
|
+
const queryClient = useQueryClient();
|
|
52
|
+
return useMutation({
|
|
53
|
+
mutationFn: ({ id, ...body }: Pick<TodoItem, 'id'> & Partial<Omit<TodoItem, 'id'>>) =>
|
|
54
|
+
doUpdateTodo(id, body),
|
|
55
|
+
onSuccess: (_data, { id }) => {
|
|
56
|
+
queryClient.invalidateQueries({ queryKey: ['todos'] });
|
|
57
|
+
queryClient.invalidateQueries({ queryKey: ['todo', id] });
|
|
58
|
+
},
|
|
59
|
+
});
|
|
37
60
|
};
|
|
38
61
|
|
|
62
|
+
export const useDeleteTodo = () => {
|
|
63
|
+
const queryClient = useQueryClient();
|
|
64
|
+
return useMutation({
|
|
65
|
+
mutationFn: doDeleteTodo,
|
|
66
|
+
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
67
|
+
});
|
|
68
|
+
};
|
|
@@ -1,9 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
import { API_Routes } from '../../constants/API_Routes';
|
|
2
|
+
import type { LoginForm, LoginResponse, TodoItem, TodoListParams } from '../redux/types';
|
|
3
|
+
import { deleteAPI, getAPI, postAPI, putAPI, uploadAPI } from './AxiosActions';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* One function per endpoint, prefixed with `do`. Screens never call these
|
|
7
|
+
* directly: wrap each one in a hook in queries.ts.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
// Auth
|
|
11
|
+
export const doLogin = (body: LoginForm) => postAPI<LoginResponse>(API_Routes.login, body);
|
|
12
|
+
|
|
13
|
+
// Todos (demo)
|
|
14
|
+
export const doGetTodos = (params: TodoListParams) => getAPI<TodoItem[]>(API_Routes.todos, params);
|
|
15
|
+
export const doGetTodoById = (id: number) => getAPI<TodoItem>(`${API_Routes.todos}/${id}`);
|
|
16
|
+
export const doAddTodo = (title: string) =>
|
|
17
|
+
postAPI<TodoItem>(API_Routes.todos, { title, completed: false });
|
|
18
|
+
export const doUpdateTodo = (id: number, body: Partial<Omit<TodoItem, 'id'>>) =>
|
|
19
|
+
putAPI<TodoItem>(`${API_Routes.todos}/${id}`, body);
|
|
20
|
+
export const doDeleteTodo = (id: number) => deleteAPI(`${API_Routes.todos}/${id}`);
|
|
21
|
+
|
|
22
|
+
// Files
|
|
23
|
+
export const doUploadFile = (body: FormData) => uploadAPI(API_Routes.uploadFile, body);
|