@umang-thakkar/base-template 1.1.1 → 1.1.2

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 CHANGED
@@ -128,11 +128,13 @@ Note: Replace MyApp with your own project name.
128
128
  <Button title="Increment" onPress={() => dispatch(increment())} />;
129
129
  ```
130
130
 
131
- ### 💾 Redux Persist (Auth Persistence)
131
+ ### 💾 MMKV & Redux Persist (Auth Persistence)
132
132
 
133
- Redux Persist is pre-configured in the template to persist the `auth` slice across app restarts. The user's data and `accessToken` survive kills and relaunches — no need to log in again.
133
+ Storage in this template is powered by [**react-native-mmkv**](https://github.com/mrousavy/react-native-mmkv), a high-performance synchronous key-value storage library.
134
134
 
135
- > `redux-persist` and `@react-native-async-storage/async-storage` are already installed and configured.
135
+ Redux Persist is pre-configured in the template to persist the `auth` slice using MMKV across app restarts. The user's data and `accessToken` survive kills and relaunches — no need to log in again.
136
+
137
+ > `react-native-mmkv`, `react-native-nitro-modules`, and `redux-persist` are already installed and configured.
136
138
 
137
139
  **What's included out of the box:**
138
140
 
@@ -145,7 +147,13 @@ Redux Persist is pre-configured in the template to persist the `auth` slice acro
145
147
  | `setAccessToken` | Updates only the `accessToken` |
146
148
  | `clearAuth` | Clears all auth state on logout |
147
149
 
148
- `src/redux/store.ts` configures `persistReducer` to persist only the `auth` slice via `AsyncStorage` and exports `persistor`.
150
+ `constants/StoragePreferences.ts` exports:
151
+ - `storage`: Raw MMKV instance for fast synchronous operations.
152
+ - `reduxStorage`: Redux Persist storage adapter backed by MMKV.
153
+ - `StorageKeys`: Predefined storage keys (`AUTH_TOKEN`, `USER_DATA`, etc.).
154
+ - Helper utilities: `getData`, `setData`, `removeData`, `removeAll`, `hasKey`, and `StoragePreferences` helper methods.
155
+
156
+ `src/redux/store.ts` configures `persistReducer` to persist only the `auth` slice via MMKV (`reduxStorage`) and exports `persistor`.
149
157
 
150
158
  `App.tsx` wraps the app with `PersistGate` so persisted state is fully rehydrated before the UI renders.
151
159
 
@@ -163,7 +171,7 @@ const dispatch = useAppDispatch();
163
171
 
164
172
  // After a successful login API call:
165
173
  dispatch(setCredentials({ user: userData, accessToken: token }));
166
- // State is automatically persisted to AsyncStorage
174
+ // State is automatically persisted to MMKV
167
175
  ```
168
176
 
169
177
  **Usage example — logout:**
@@ -173,7 +181,21 @@ import { useAppDispatch } from "../redux/store";
173
181
  import { clearAuth } from "../redux/slices/authSlice";
174
182
 
175
183
  const dispatch = useAppDispatch();
176
- dispatch(clearAuth()); // Clears Redux state and AsyncStorage
184
+ dispatch(clearAuth()); // Clears Redux state and MMKV persisted auth
185
+ ```
186
+
187
+ **Usage example — direct MMKV key-value storage:**
188
+
189
+ ```tsx
190
+ import { StoragePreferences, getData, setData } from "../constants/StoragePreferences";
191
+
192
+ // Synchronous and fast!
193
+ setData("theme_mode", "dark");
194
+ const theme = getData("theme_mode");
195
+
196
+ // Or using StoragePreferences helper:
197
+ StoragePreferences.setString("username", "John");
198
+ const username = StoragePreferences.getString("username");
177
199
  ```
178
200
 
179
201
  **Usage example — read auth state:**
@@ -186,9 +208,9 @@ const { user, accessToken } = useAppSelector((state) => state.auth);
186
208
 
187
209
  **How it works end-to-end:**
188
210
 
189
- - On login → dispatch `setCredentials` → persisted to `AsyncStorage`
211
+ - On login → dispatch `setCredentials` → persisted to MMKV via `reduxStorage`
190
212
  - On app restart → `PersistGate` rehydrates `auth` → `SplashScreen` sees `accessToken` → navigates directly to `HomeScreen`
191
- - On logout → dispatch `clearAuth` → persisted data cleared → `SplashScreen` routes to `LoginScreen`
213
+ - On logout → dispatch `clearAuth` → persisted data cleared from MMKV → `SplashScreen` routes to `LoginScreen`
192
214
 
193
215
  ### 🌙 Dark/Light Theme Support
194
216
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umang-thakkar/base-template",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "The template for react native to setup redux and other neccesary boilerplate codes",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -0,0 +1,59 @@
1
+ const mockStorage = new Map<string, any>();
2
+
3
+ export class MMKVMock {
4
+ set(key: string, value: boolean | string | number | Uint8Array) {
5
+ mockStorage.set(key, value);
6
+ }
7
+
8
+ getString(key: string): string | undefined {
9
+ const val = mockStorage.get(key);
10
+ return typeof val === "string" ? val : undefined;
11
+ }
12
+
13
+ getBoolean(key: string): boolean | undefined {
14
+ const val = mockStorage.get(key);
15
+ return typeof val === "boolean" ? val : undefined;
16
+ }
17
+
18
+ getNumber(key: string): number | undefined {
19
+ const val = mockStorage.get(key);
20
+ return typeof val === "number" ? val : undefined;
21
+ }
22
+
23
+ getBuffer(key: string): Uint8Array | undefined {
24
+ const val = mockStorage.get(key);
25
+ return val instanceof Uint8Array ? val : undefined;
26
+ }
27
+
28
+ contains(key: string): boolean {
29
+ return mockStorage.has(key);
30
+ }
31
+
32
+ remove(key: string) {
33
+ mockStorage.delete(key);
34
+ }
35
+
36
+ delete(key: string) {
37
+ mockStorage.delete(key);
38
+ }
39
+
40
+ clearAll() {
41
+ mockStorage.clear();
42
+ }
43
+
44
+ getAllKeys(): string[] {
45
+ return Array.from(mockStorage.keys());
46
+ }
47
+
48
+ addOnValueChangedListener() {
49
+ return { remove: () => {} };
50
+ }
51
+ }
52
+
53
+ export const MMKV = MMKVMock;
54
+
55
+ export function createMMKV() {
56
+ return new MMKVMock();
57
+ }
58
+
59
+ export default createMMKV;
@@ -1,94 +1,172 @@
1
- import AsyncStorage from "@react-native-async-storage/async-storage";
1
+ import { createMMKV, MMKV } from "react-native-mmkv";
2
+ import type { Storage } from "redux-persist";
2
3
 
3
4
  /**
4
- * Retrieves data from AsyncStorage with optional JSON parsing.
5
+ * MMKV storage instance.
6
+ * Supports MMKV v4 (createMMKV) and v3 (new MMKV()).
7
+ */
8
+ export const storage =
9
+ typeof createMMKV === "function" ? createMMKV() : new (MMKV as any)();
10
+
11
+ /**
12
+ * Predefined storage keys used across the application.
13
+ */
14
+ export const StorageKeys = {
15
+ AUTH_TOKEN: "auth_token",
16
+ USER_DATA: "user_data",
17
+ THEME_MODE: "theme_mode",
18
+ LANGUAGE: "language",
19
+ IS_FIRST_TIME: "is_first_time",
20
+ } as const;
21
+
22
+ export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys] | string;
23
+
24
+ /**
25
+ * Redux-persist compatible storage engine backed by MMKV.
26
+ * Adapts MMKV's synchronous API to the Promise-based interface expected by redux-persist.
27
+ */
28
+ export const reduxStorage: Storage = {
29
+ setItem: (key: string, value: string): Promise<boolean> => {
30
+ storage.set(key, value);
31
+ return Promise.resolve(true);
32
+ },
33
+ getItem: (key: string): Promise<string | null> => {
34
+ const value = storage.getString(key);
35
+ return Promise.resolve(value ?? null);
36
+ },
37
+ removeItem: (key: string): Promise<void> => {
38
+ if (typeof (storage as any).remove === "function") {
39
+ (storage as any).remove(key);
40
+ } else if (typeof (storage as any).delete === "function") {
41
+ (storage as any).delete(key);
42
+ }
43
+ return Promise.resolve();
44
+ },
45
+ };
46
+
47
+ /**
48
+ * Retrieves data from MMKV with optional JSON parsing (Synchronous).
5
49
  * @param key - The key of the item to retrieve.
6
50
  * @param parseJSON - Whether to parse the value as JSON (default: false).
7
51
  * @returns The stored value or null if not found.
8
52
  */
9
- export const getData = async <T = string>(
10
- key: string,
11
- parseJSON: boolean = false
12
- ): Promise<T | null> => {
13
- try {
14
- const value = await AsyncStorage.getItem(key);
15
-
16
- if (value === null) return null;
53
+ export const getData = <T = string>(
54
+ key: string,
55
+ parseJSON: boolean = false
56
+ ): T | null => {
57
+ try {
58
+ const value = storage.getString(key);
17
59
 
18
- if (parseJSON) {
19
- try {
20
- return JSON.parse(value) as T;
21
- } catch (parseError) {
22
- console.warn(`Failed to parse JSON for key "${key}":`, parseError);
23
- return value as T;
24
- }
25
- }
60
+ if (value === undefined || value === null) {
61
+ return null;
62
+ }
26
63
 
27
- return value as T;
28
- } catch (error) {
29
- console.error(`Error retrieving data for key "${key}":`, error);
30
- return null;
64
+ if (parseJSON) {
65
+ try {
66
+ return JSON.parse(value) as T;
67
+ } catch (parseError) {
68
+ console.warn(`Failed to parse JSON for key "${key}":`, parseError);
69
+ return value as unknown as T;
70
+ }
31
71
  }
72
+
73
+ return value as unknown as T;
74
+ } catch (error) {
75
+ console.error(`Error retrieving data for key "${key}":`, error);
76
+ return null;
77
+ }
32
78
  };
33
79
 
34
80
  /**
35
- * Stores data in AsyncStorage with automatic JSON stringification for objects.
81
+ * Stores data in MMKV with automatic JSON stringification for objects/arrays (Synchronous).
36
82
  * @param key - The key to store the item under.
37
83
  * @param value - The value to store.
38
84
  * @returns True if successful, false otherwise.
39
85
  */
40
- export const setData = async<T>(key: string, value: T) : Promise<boolean> => {
86
+ export const setData = <T>(key: string, value: T): boolean => {
41
87
  try {
42
- const stringValue =
43
- typeof value === "string" ? value : JSON.stringify(value);
44
- await AsyncStorage.setItem(key, stringValue);
88
+ if (typeof value === "string") {
89
+ storage.set(key, value);
90
+ } else if (typeof value === "number") {
91
+ storage.set(key, value);
92
+ } else if (typeof value === "boolean") {
93
+ storage.set(key, value);
94
+ } else {
95
+ storage.set(key, JSON.stringify(value));
96
+ }
45
97
  return true;
46
98
  } catch (error) {
47
- console.error(`Error storing data for key "${key}":`, error);
99
+ console.error(`Error storing data for key "${key}":`, error);
48
100
  return false;
49
101
  }
50
102
  };
51
103
 
52
- /**
53
- * Removes a single item from AsyncStorage.
54
- * @param key - The key of the item to remove.
55
- * @returns True if successful, false otherwise.
56
- */
57
- export const removeData = async (key: string): Promise<boolean> => {
104
+ /**
105
+ * Removes a single item from MMKV (Synchronous).
106
+ * @param key - The key of the item to remove.
107
+ * @returns True if successful, false otherwise.
108
+ */
109
+ export const removeData = (key: string): boolean => {
58
110
  try {
59
- await AsyncStorage.removeItem(key);
60
- return true;
111
+ if (typeof (storage as any).remove === "function") {
112
+ (storage as any).remove(key);
113
+ } else if (typeof (storage as any).delete === "function") {
114
+ (storage as any).delete(key);
115
+ }
116
+ return true;
61
117
  } catch (error) {
62
- console.error(`Error removing data for key "${key}":`, error);
63
- return false;
118
+ console.error(`Error removing data for key "${key}":`, error);
119
+ return false;
64
120
  }
65
121
  };
66
122
 
67
- /**
68
- * Clears all data from AsyncStorage.
69
- * @returns True if successful, false otherwise.
70
- */
71
- export const removeAll = async (): Promise<boolean> => {
123
+ /**
124
+ * Clears all data from MMKV (Synchronous).
125
+ * @returns True if successful, false otherwise.
126
+ */
127
+ export const removeAll = (): boolean => {
72
128
  try {
73
- await AsyncStorage.clear();
74
- return true;
129
+ storage.clearAll();
130
+ return true;
75
131
  } catch (error) {
76
- console.error("Error clearing all storage:", error);
77
- return false;
132
+ console.error("Error clearing all storage:", error);
133
+ return false;
78
134
  }
79
135
  };
80
136
 
81
- /**
82
- * Checks if a key exists in AsyncStorage.
83
- * @param key - The key to check.
84
- * @returns True if key exists, false otherwise.
85
- */
86
- export const hasKey = async (key: string): Promise<boolean> => {
137
+ /**
138
+ * Checks if a key exists in MMKV (Synchronous).
139
+ * @param key - The key to check.
140
+ * @returns True if key exists, false otherwise.
141
+ */
142
+ export const hasKey = (key: string): boolean => {
87
143
  try {
88
- const value = await AsyncStorage.getItem(key);
89
- return value !== null;
144
+ return storage.contains(key);
90
145
  } catch (error) {
91
- console.error(`Error checking key "${key}":`, error);
92
- return false;
146
+ console.error(`Error checking key "${key}":`, error);
147
+ return false;
93
148
  }
94
149
  };
150
+
151
+ /**
152
+ * Helper object providing convenient type-safe access to MMKV.
153
+ */
154
+ export const StoragePreferences = {
155
+ storage,
156
+ reduxStorage,
157
+ keys: StorageKeys,
158
+ get: getData,
159
+ set: setData,
160
+ getString: (key: string): string | undefined => storage.getString(key),
161
+ setString: (key: string, value: string): void => storage.set(key, value),
162
+ getNumber: (key: string): number | undefined => storage.getNumber(key),
163
+ setNumber: (key: string, value: number): void => storage.set(key, value),
164
+ getBoolean: (key: string): boolean | undefined => storage.getBoolean(key),
165
+ setBoolean: (key: string, value: boolean): void => storage.set(key, value),
166
+ remove: removeData,
167
+ removeAll,
168
+ hasKey,
169
+ getAllKeys: (): string[] => storage.getAllKeys(),
170
+ };
171
+
172
+ export default StoragePreferences;
@@ -10,7 +10,6 @@
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
15
  "@react-navigation/stack": "^7.10.5",
@@ -21,10 +20,12 @@
21
20
  "react": "19.2.3",
22
21
  "react-native": "0.84.0",
23
22
  "react-native-gesture-handler": "^3.0.1",
23
+ "react-native-mmkv": "^4.3.2",
24
+ "react-native-nitro-modules": "^0.35.0",
25
+ "react-native-reanimated": "^4.4.1",
24
26
  "react-native-safe-area-context": "^5.8.0",
25
27
  "react-native-screens": "^4.25.0",
26
28
  "react-native-svg": "^15.12.1",
27
- "react-native-reanimated": "^4.4.1",
28
29
  "react-native-worklets": "^0.10.0",
29
30
  "react-redux": "^9.3.0",
30
31
  "redux-persist": "^6.0.0"
@@ -0,0 +1,32 @@
1
+ import { Dimensions } from "react-native";
2
+
3
+ const { width, height } = Dimensions.get("window");
4
+
5
+ const guidelineBaseWidth: number = 390;
6
+ const guidelineBaseHeight: number = 844;
7
+
8
+ export const isTablet = width >= 768;
9
+ const tabletMaxWidth = 550;
10
+ const tabletMaxHeight = 900;
11
+
12
+ const effectiveWidth = isTablet ? Math.min(width, tabletMaxWidth) : width;
13
+ const effectiveHeight = isTablet ? Math.min(height, tabletMaxHeight) : height;
14
+
15
+ const horizontalScale = (size: number): number =>
16
+ (effectiveWidth / guidelineBaseWidth) * size;
17
+
18
+ const verticalScale = (size: number): number =>
19
+ (effectiveHeight / guidelineBaseHeight) * size;
20
+
21
+ const moderateScale = (size: number, factor: number = 0.5): number =>
22
+ size + (horizontalScale(size) - size) * factor;
23
+
24
+ const getResponsiveIconSize = (baseSize = 100) => {
25
+ const scaleFactor = Math.min(
26
+ effectiveWidth / guidelineBaseWidth,
27
+ effectiveHeight / guidelineBaseHeight,
28
+ );
29
+ return baseSize * scaleFactor;
30
+ };
31
+
32
+ export { horizontalScale, verticalScale, moderateScale, getResponsiveIconSize };
@@ -1,85 +1,63 @@
1
1
  // utils.ts
2
- import { Dimensions, Platform, PixelRatio, Keyboard, Alert } from "react-native";
3
- const { width, height } = Dimensions.get("window");
2
+ import {
3
+ Dimensions,
4
+ Platform,
5
+ PixelRatio,
6
+ Keyboard,
7
+ Alert,
8
+ } from "react-native";
4
9
 
5
- // Get device dimensions
6
- export const deviceWidth = width;
7
- export const deviceHeight = height;
10
+ const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
8
11
 
9
- // Platform checks
10
- export const isAndroid = Platform.OS === "android";
11
12
  export const isIOS = Platform.OS === "ios";
13
+ export const isAndroid = Platform.OS === "android";
14
+ export const deviceWidth = SCREEN_WIDTH;
15
+ export const deviceHeight = SCREEN_HEIGHT;
12
16
 
13
- // Responsive font size
14
- export function responsiveFontSize(size: number) {
15
- const scale = width / 375; // base width: iPhone 11
16
- const newSize = size * scale;
17
- return Math.round(PixelRatio.roundToNearestPixel(newSize));
18
- }
17
+ const scale = SCREEN_WIDTH / 390;
19
18
 
20
- export const responsiveHeight = (value: number) => {
21
- let temp = value;
22
- if (deviceHeight != 896) {
23
- let temp2 = (value / 896).toFixed(4);
24
- temp = PixelRatio.roundToNearestPixel(deviceHeight * Number(temp2));
25
- }
26
- return temp;
19
+ export const responsiveFontSize = (size: number): number => {
20
+ const newSize = size * scale;
21
+ if (isIOS) {
22
+ return Math.round(PixelRatio.roundToNearestPixel(newSize));
23
+ } else {
24
+ return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 1;
25
+ }
27
26
  };
28
27
 
29
- export const responsiveWidth = (value: number) => {
30
- let temp = value;
31
- if (deviceWidth !== 414) {
32
- let temp2 = (value / 414).toFixed(4); // 414 is a common base width (e.g., iPhone 11)
33
- temp = PixelRatio.roundToNearestPixel(deviceWidth * Number(temp2));
34
- }
35
- return temp;
28
+ export const responsiveHeight = (height: number): number => {
29
+ return Math.round((SCREEN_HEIGHT / 844) * height);
36
30
  };
37
31
 
38
- // Check if device is small, medium, large (useful for UI adjustments)
39
- export function getDeviceType() {
40
- if (width < 360) return "small";
41
- if (width < 768) return "medium";
42
- return "large";
43
- }
44
-
45
- // Example: normalize size for both iOS/Android
46
- export function normalize(size: number) {
47
- const scale = width / 375;
48
- const newSize = size * scale;
49
- if (isIOS) {
50
- return Math.round(PixelRatio.roundToNearestPixel(newSize));
51
- } else {
52
- return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2;
53
- }
54
- }
32
+ export const responsiveWidth = (width: number): number => {
33
+ return Math.round((SCREEN_WIDTH / 390) * width);
34
+ };
55
35
 
56
36
  export const hideKeyboard = () => {
57
- Keyboard.dismiss();
37
+ Keyboard.dismiss();
58
38
  };
59
39
 
60
40
  export const showAlert = (
61
- title: string,
62
- message: string,
63
- settingsText = 'Open Settings',
64
- rejectText = 'Reject',
65
- onSettingsPress: () => void
41
+ title: string,
42
+ message: string,
43
+ settingsText = "Open Settings",
44
+ rejectText = "Reject",
45
+ onSettingsPress: () => void,
66
46
  ) => {
67
- Alert.alert(
68
- title,
69
- message,
70
- [
71
- {
72
- text: settingsText,
73
- onPress: onSettingsPress,
74
- style: 'default',
75
- },
76
- {
77
- text: rejectText,
78
- style: 'destructive',
79
- },
80
- ],
81
- { cancelable: false }
82
- );
47
+ Alert.alert(
48
+ title,
49
+ message,
50
+ [
51
+ {
52
+ text: settingsText,
53
+ onPress: onSettingsPress,
54
+ style: "default",
55
+ },
56
+ {
57
+ text: rejectText,
58
+ style: "destructive",
59
+ },
60
+ ],
61
+ { cancelable: false },
62
+ );
83
63
  };
84
-
85
-
@@ -3,10 +3,10 @@ import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
3
3
  import { persistReducer, persistStore } from "redux-persist";
4
4
  import reducer from "./slice";
5
5
  import authReducer from "./slices/authSlice";
6
- import AsyncStorage from "@react-native-async-storage/async-storage";
6
+ import { reduxStorage } from "../../constants/StoragePreferences";
7
7
  const persistConfig = {
8
8
  key: "root",
9
- storage: AsyncStorage,
9
+ storage: reduxStorage,
10
10
  whitelist: ["auth"],
11
11
  };
12
12