@umang-thakkar/base-template 1.1.2 → 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.
Files changed (45) hide show
  1. package/README.md +40 -304
  2. package/package.json +11 -2
  3. package/template/.eslintrc +16 -46
  4. package/template/.prettierrc.js +8 -0
  5. package/template/App.tsx +11 -15
  6. package/template/Main.tsx +29 -5
  7. package/template/__mocks__/react-native-mmkv.ts +4 -4
  8. package/template/__tests__/App.test.tsx +6 -1
  9. package/template/__tests__/helpers.test.ts +43 -0
  10. package/template/babel.config.js +2 -1
  11. package/template/constants/API_Routes.ts +19 -0
  12. package/template/constants/AppConstants.tsx +1 -1
  13. package/template/constants/AppString.ts +36 -0
  14. package/template/constants/StoragePreferences.ts +16 -31
  15. package/template/jest.config.js +5 -0
  16. package/template/jest.setup.js +5 -0
  17. package/template/package.json +2 -3
  18. package/template/src/api/AxiosActions.ts +65 -28
  19. package/template/src/api/AxiosClient.ts +13 -7
  20. package/template/src/api/queries.ts +59 -29
  21. package/template/src/api/service.ts +23 -9
  22. package/template/src/components/ErrorBoundary.tsx +27 -31
  23. package/template/src/components/SnackbarHost.tsx +86 -0
  24. package/template/src/helper/colors.ts +22 -22
  25. package/template/src/helper/common-functions.ts +56 -10
  26. package/template/src/helper/matrics.ts +4 -6
  27. package/template/src/helper/navigation-service.ts +21 -24
  28. package/template/src/helper/snackbar.ts +41 -0
  29. package/template/src/helper/typography.ts +2 -2
  30. package/template/src/helper/utility-functions.ts +10 -16
  31. package/template/src/hooks/ThemeContext.tsx +60 -30
  32. package/template/src/hooks/usePaginatedAPI.ts +96 -0
  33. package/template/src/navigation/AppStack.tsx +36 -27
  34. package/template/src/navigation/screens.ts +17 -11
  35. package/template/src/redux/slice.ts +17 -12
  36. package/template/src/redux/slices/authSlice.ts +11 -14
  37. package/template/src/redux/store.ts +13 -9
  38. package/template/src/redux/types.d.ts +40 -19
  39. package/template/src/screens/HomeScreen.tsx +103 -29
  40. package/template/src/screens/LoginScreen.tsx +101 -69
  41. package/template/src/screens/SplashScreen.tsx +36 -25
  42. package/template/src/theme/darkTheme.ts +13 -6
  43. package/template/src/theme/index.ts +4 -3
  44. package/template/src/theme/lightTheme.ts +13 -5
  45. package/template/ios/.xcode.env.local +0 -1
package/README.md CHANGED
@@ -1,324 +1,60 @@
1
1
  # 🚀 React Native Base Template
2
2
 
3
- A React Native boilerplate to kickstart your mobile app development faster, with preconfigured essentials like:
3
+ A React Native CLI template with the boilerplate already done: Redux Toolkit, Redux Persist on MMKV, React Navigation, React Query, Axios, light/dark theming and TypeScript. Styling uses plain `StyleSheet`.
4
4
 
5
- - 🔁 Redux Toolkit for scalable state management
6
- - 💾 Redux Persist for auth persistence across sessions
7
- - 📍 React Navigation for robust navigation
8
- - 🔗 React Query for powerful API data fetching and caching
9
- - 🌙 Dark/Light theme support with system preference detection
10
- - 🗂️ Scalable folder structure
11
- - 🧰 Common utility functions
12
- - 📦 Pre-installed useful dependencies
13
- - ⚙️ Optimized project setup for faster development
5
+ > Prefer Tailwind-style `className` styling? Use the NativeWind variant: [`@umang-thakkar/base-template-nativewind`](https://www.npmjs.com/package/@umang-thakkar/base-template-nativewind).
14
6
 
15
- ## 📦 Features
7
+ ## Quick start
16
8
 
17
- - ✅ Redux Toolkit with example slices and hooks
18
- - ✅ Redux Persist with auth slice persistence (user data + access token)
19
- - ✅ React Navigation with Stack Navigator setup
20
- - ✅ React Query for API management (see `src/api/queries.ts`)
21
- - ✅ Dark/Light theme support with automatic system detection
22
- - ✅ Organized folder structure for features, helpers, navigation, etc.
23
- - ✅ Useful helpers: debouncers, formatters, navigation service
24
- - ✅ TypeScript support
25
- - ✅ Common third-party libraries installed
26
-
27
- ## 📁 Folder Structure
28
-
29
- ```
30
- template/
31
- ├── App.tsx # Entry point
32
- ├── Main.tsx # Main app logic
33
- ├── app.json # App config
34
- ├── babel.config.js # Babel config
35
- ├── constants/ # App constants
36
- │ ├── AppConstants.tsx
37
- │ └── StoragePreferences.ts
38
- ├── __tests__/ # Test files
39
- │ └── App.test.tsx
40
- ├── android/ # Android project files
41
- ├── ios/ # iOS project files
42
- ├── src/
43
- │ ├── api/ # API clients, actions, and React Query hooks
44
- │ │ ├── AxiosActions.ts
45
- │ │ ├── AxiosClient.ts
46
- │ │ ├── queries.ts # React Query hooks and API calls
47
- │ │ └── service.ts
48
- │ ├── assets/ # Fonts, images, svg
49
- │ │ ├── fonts/
50
- │ │ ├── images/
51
- │ │ └── svg/
52
- │ ├── helper/ # Utility and helper functions
53
- │ │ ├── colors.ts
54
- │ │ ├── common-functions.ts
55
- │ │ ├── font-family.ts
56
- │ │ ├── navigation-service.ts
57
- │ │ ├── typography.ts
58
- │ │ └── utility-functions.ts
59
- │ ├── hooks/ # Custom hooks
60
- │ │ └── ThemeContext.tsx # Theme context and provider
61
- │ ├── navigation/ # Navigation setup
62
- │ │ ├── AppStack.tsx
63
- │ │ ├── AppStackParams.ts
64
- │ │ └── screens.ts
65
- │ ├── redux/ # Redux store, slices, types
66
- │ │ ├── action.ts
67
- │ │ ├── slices/
68
- │ │ │ └── authSlice.ts # Auth slice with user data + token state
69
- │ │ ├── store.ts # Store with redux-persist configuration
70
- │ │ └── types.d.ts
71
- │ ├── screens/ # App screens
72
- │ │ ├── HomeScreen.tsx
73
- │ │ ├── LoginScreen.tsx # Demo login screen — saves user + token to auth slice
74
- │ │ └── SplashScreen.tsx # Reads accessToken from Redux to decide initial route
75
- │ ├── theme/ # Theme configuration
76
- │ │ ├── darkTheme.ts # Dark theme colors
77
- │ │ ├── lightTheme.ts # Light theme colors
78
- │ │ └── index.ts # Theme exports and types
79
- ├── vendor/ # Vendor files
80
- │ └── bundle/
81
- ├── package.json # Project dependencies
82
- ├── tsconfig.json # TypeScript config
83
- └── README.md # Template README
84
- ```
85
-
86
- ## 🚀 Getting Started
87
-
88
- 1. Create a new project using this template:
89
- ```sh
90
- npx @react-native-community/cli init MyApp --template @umang-thakkar/base-template
91
- ```
92
-
93
- ```
94
- Note: Replace MyApp with your own project name.
9
+ ```sh
10
+ npx @react-native-community/cli init MyApp --template @umang-thakkar/base-template
11
+ cd MyApp
12
+ npm start
95
13
  ```
96
14
 
97
- 2. Install dependencies:
98
- ```sh
99
- npm install
100
- ```
101
- 3. Start Metro server:
102
- ```sh
103
- npx react-native start
104
- ```
105
- 4. Run the app:
106
-
107
- ```sh
108
- # For Android
109
- npx react-native run-android
110
-
111
- # For iOS
112
- npx react-native run-ios
113
- ```
114
-
115
- > **Note**: With React Native 0.60+, iOS dependencies are automatically linked using autolinking. Manual pod installation is no longer required for most cases.
116
-
117
- ## 🧠 Usage Instructions
118
-
119
- ### 📌 Redux Toolkit
120
-
121
- - Store is configured in `src/redux/store.ts`.
122
- - Example usage:
123
- ```tsx
124
- import { useAppSelector, useAppDispatch } from "../redux/store";
125
- import { increment } from "../redux/slice";
126
- const count = useAppSelector((state) => state.counter.value);
127
- const dispatch = useAppDispatch();
128
- <Button title="Increment" onPress={() => dispatch(increment())} />;
129
- ```
130
-
131
- ### 💾 MMKV & Redux Persist (Auth Persistence)
132
-
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.
15
+ Then, in another terminal, `npm run android` or `npm run ios`. Requires Node.js 22.11+.
134
16
 
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.
17
+ ## What's included
136
18
 
137
- > `react-native-mmkv`, `react-native-nitro-modules`, and `redux-persist` are already installed and configured.
19
+ - **Redux Toolkit** store with typed hooks and an `auth` slice (`user` + `accessToken`, typed selectors)
20
+ - **Redux Persist on MMKV**: login survives app restarts
21
+ - **React Navigation 7** native stack with a screen registry, per-screen options and a navigation service for use outside components
22
+ - **React Query 5** hooks over a layered **Axios** API (client → actions → services → queries), with an interceptor that attaches the auth token
23
+ - **Infinite scroll** helper `usePaginatedAPI` with debounced search
24
+ - **Light/dark themes** via `useTheme()`; the user's Light / Dark / System choice is saved in MMKV, and the navigation theme and status bar follow it
25
+ - App-wide **snackbars** (`showSnackbar` / `showErrorSnackbar`) and `getErrorMessage` for API errors
26
+ - Central `API_Routes` and `AppString` constants
27
+ - **ErrorBoundary** with a dev-only error view
28
+ - Responsive scaling, typography presets, formatting, date and platform helpers
29
+ - ESLint (React, TypeScript, React Native, React Query), Prettier, and Jest with MMKV and Reanimated mocks
30
+ - An agent skill (`.agents/skills/umang-design-pattern` in the repo) describing the conventions, so AI coding agents build apps the same way
138
31
 
139
- **What's included out of the box:**
140
-
141
- `src/redux/slices/authSlice.ts` stores `user` and `accessToken` with the following actions:
142
-
143
- | Action | Description |
144
- | ---------------- | ---------------------------------------------- |
145
- | `setCredentials` | Sets both `user` and `accessToken` after login |
146
- | `setUser` | Updates only the `user` object |
147
- | `setAccessToken` | Updates only the `accessToken` |
148
- | `clearAuth` | Clears all auth state on logout |
149
-
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`.
157
-
158
- `App.tsx` wraps the app with `PersistGate` so persisted state is fully rehydrated before the UI renders.
159
-
160
- `src/screens/SplashScreen.tsx` reads `accessToken` from Redux on startup — if present, navigates to `HomeScreen`, otherwise to `LoginScreen`.
161
-
162
- `src/screens/LoginScreen.tsx` is a demo login screen that dispatches `setCredentials` with dummy `user` and `accessToken` data to demonstrate the persistence flow.
163
-
164
- **Usage example — login:**
165
-
166
- ```tsx
167
- import { useAppDispatch } from "../redux/store";
168
- import { setCredentials } from "../redux/slices/authSlice";
169
-
170
- const dispatch = useAppDispatch();
171
-
172
- // After a successful login API call:
173
- dispatch(setCredentials({ user: userData, accessToken: token }));
174
- // State is automatically persisted to MMKV
175
- ```
176
-
177
- **Usage example — logout:**
178
-
179
- ```tsx
180
- import { useAppDispatch } from "../redux/store";
181
- import { clearAuth } from "../redux/slices/authSlice";
182
-
183
- const dispatch = useAppDispatch();
184
- dispatch(clearAuth()); // Clears Redux state and MMKV persisted auth
185
- ```
32
+ ## Documentation
186
33
 
187
- **Usage example — direct MMKV key-value storage:**
34
+ Full docs are in [`docs/`](./docs/README.md):
188
35
 
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");
199
- ```
200
-
201
- **Usage example — read auth state:**
202
-
203
- ```tsx
204
- import { useAppSelector } from "../redux/store";
205
-
206
- const { user, accessToken } = useAppSelector((state) => state.auth);
207
- ```
208
-
209
- **How it works end-to-end:**
210
-
211
- - On login → dispatch `setCredentials` → persisted to MMKV via `reduxStorage`
212
- - On app restart → `PersistGate` rehydrates `auth` → `SplashScreen` sees `accessToken` → navigates directly to `HomeScreen`
213
- - On logout → dispatch `clearAuth` → persisted data cleared from MMKV → `SplashScreen` routes to `LoginScreen`
214
-
215
- ### 🌙 Dark/Light Theme Support
216
-
217
- The template includes a complete theming system with automatic system preference detection:
218
-
219
- - **Theme files**: Located in `src/theme/`
220
- - `darkTheme.ts` - Dark theme colors
221
- - `lightTheme.ts` - Light theme colors
222
- - `index.ts` - Theme exports and TypeScript types
223
-
224
- - **Theme Context**: `src/hooks/ThemeContext.tsx` provides theme management
225
-
226
- - **Usage in components**:
227
-
228
- ```tsx
229
- import { useTheme } from "../hooks/ThemeContext";
230
-
231
- const MyComponent = () => {
232
- const { theme, mode, toggleTheme } = useTheme();
233
-
234
- return (
235
- <View style={{ backgroundColor: theme.background }}>
236
- <Text style={{ color: theme.text }}>Current theme: {mode}</Text>
237
- <TouchableOpacity
238
- style={{ backgroundColor: theme.primary }}
239
- onPress={toggleTheme}
240
- >
241
- <Text style={{ color: theme.text }}>Toggle Theme</Text>
242
- </TouchableOpacity>
243
- </View>
244
- );
245
- };
246
- ```
247
-
248
- - **Features**:
249
- - Automatic detection of system color scheme preference
250
- - Manual theme toggle functionality
251
- - Listens for system theme changes
252
- - TypeScript support for theme properties
253
-
254
- ### 🌐 Navigation
255
-
256
- - Navigation setup in `src/navigation/`.
257
- - Register screens in `AppStack.tsx`.
258
-
259
- ### 🔗 React Query
260
-
261
- - API calls and React Query hooks are in `src/api/queries.ts`.
262
- - Example usage:
263
- ```ts
264
- import { useQuery } from "@tanstack/react-query";
265
- import { fetchData } from "../api/queries";
266
- const { data, isLoading } = useQuery({
267
- queryKey: ["data"],
268
- queryFn: fetchData,
269
- });
270
- ```
271
-
272
- ### 🧰 Utility Functions
273
-
274
- - Use helpers from `src/helper/`:
275
- ```ts
276
- import { formatDate } from "../helper/common-functions";
277
- ```
278
-
279
- ## 🪄 Customization Tips
280
-
281
- - Add new slices under `src/redux/`
282
- - Add new API services under `src/api/`
283
- - Organize screens under `src/screens/`
284
- - Keep shared components in a `components/` folder (add as needed)
285
- - Customize theme colors in `src/theme/darkTheme.ts` and `src/theme/lightTheme.ts`
286
- - Extend theme properties by updating the theme type in `src/theme/index.ts`
287
- - To persist additional slices, create a separate `persistConfig` per slice and wrap with `persistReducer`
288
- - To exclude sensitive fields from persistence, use the `blacklist` array in the persist config instead of `whitelist`
289
-
290
- ## 🎨 Theme Customization
291
-
292
- To customize the theme colors, edit the theme files:
293
-
294
- ```ts
295
- // src/theme/lightTheme.ts
296
- export const lightTheme = {
297
- background: "#FFFFFF",
298
- text: "#000000",
299
- primary: "#4045EF",
300
- secondary: "#F4F4F4",
301
- // Add your custom colors here
302
- };
303
-
304
- // src/theme/darkTheme.ts
305
- export const darkTheme = {
306
- background: "#000000",
307
- text: "#FFFFFF",
308
- primary: "#4045EF",
309
- secondary: "#1A1A1A",
310
- // Add your custom colors here
311
- };
312
- ```
36
+ - [Getting Started](./docs/getting-started.md)
37
+ - [Project Structure](./docs/project-structure.md)
38
+ - [State Management](./docs/state-management.md)
39
+ - [Storage (MMKV)](./docs/storage.md)
40
+ - [Networking](./docs/networking.md)
41
+ - [Navigation](./docs/navigation.md)
42
+ - [Theming](./docs/theming.md)
43
+ - [Helpers & Utilities](./docs/helpers.md)
44
+ - [Error Handling](./docs/error-handling.md)
45
+ - [Code Quality & Testing](./docs/code-quality.md)
46
+ - [Customization Recipes](./docs/customization.md)
47
+ - [Roadmap & Known Issues](./docs/roadmap.md)
48
+ - [Publishing the Template](./docs/publishing.md)
313
49
 
314
- ## 🤝 Contributing
50
+ ## Contributing
315
51
 
316
- Feel free to fork and customize this template! Pull requests welcome.
52
+ Fork it and customize it. Pull requests are welcome.
317
53
 
318
- ## 👨‍💻 Author
54
+ ## Author
319
55
 
320
56
  Created with ❤️ by **[Umang Thakkar](https://github.com/Umang2809)**
321
57
 
322
- ## 📜 License
58
+ ## License
323
59
 
324
60
  MIT © [Umang Thakkar](https://github.com/Umang2809)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umang-thakkar/base-template",
3
- "version": "1.1.2",
3
+ "version": "1.2.0",
4
4
  "description": "The template for react native to setup redux and other neccesary boilerplate codes",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -12,7 +12,16 @@
12
12
  "type": "commonjs",
13
13
  "files": [
14
14
  "template/*",
15
- "template.config.js"
15
+ "template.config.js",
16
+ "!template/node_modules",
17
+ "!template/ios/Pods",
18
+ "!template/ios/build",
19
+ "!template/android/build",
20
+ "!template/android/app/build",
21
+ "!template/android/.gradle",
22
+ "!template/ios/.xcode.env.local",
23
+ "!template/package-lock.json",
24
+ "!template/yarn.lock"
16
25
  ],
17
26
  "dependencies": {},
18
27
  "devDependencies": {
@@ -2,7 +2,6 @@
2
2
  "root": true,
3
3
  "extends": [
4
4
  "@react-native",
5
- "@react-native-community",
6
5
  "plugin:@tanstack/eslint-plugin-query/recommended",
7
6
  ],
8
7
  "parser": "@typescript-eslint/parser",
@@ -26,6 +25,11 @@
26
25
  "node": true,
27
26
  "react-native/react-native": true,
28
27
  },
28
+ "settings": {
29
+ "react": {
30
+ "version": "detect",
31
+ },
32
+ },
29
33
  "rules": {
30
34
  // React best practices
31
35
  "react/react-in-jsx-scope": "off",
@@ -43,14 +47,14 @@
43
47
  },
44
48
  ],
45
49
  "@typescript-eslint/no-explicit-any": "warn",
46
- "@typescript-eslint/explicit-function-return-types": "off",
47
50
  "@typescript-eslint/no-non-null-assertion": "warn",
48
51
 
49
- // React Native best practices
52
+ // Styling: StyleSheet.create at the bottom of each file, theme colors from
53
+ // useTheme(), no literal colors or inline style objects.
50
54
  "react-native/no-unused-styles": "warn",
51
- "react-native/split-platform-components": "warn",
52
55
  "react-native/no-inline-styles": "warn",
53
56
  "react-native/no-color-literals": "warn",
57
+ "react-native/split-platform-components": "warn",
54
58
 
55
59
  // General best practices
56
60
  "no-console": [
@@ -64,51 +68,9 @@
64
68
  "prefer-const": "error",
65
69
  "eqeqeq": ["error", "always"],
66
70
  "curly": ["error", "all"],
67
- "brace-style": ["error", "1tbs"],
68
- "space-before-function-paren": [
69
- "error",
70
- {
71
- "anonymous": "always",
72
- "named": "never",
73
- "asyncArrow": "always",
74
- },
75
- ],
76
- "semi": ["error", "always"],
77
- "quotes": ["error", "single", { "avoidEscape": true }],
78
- "indent": ["error", 2],
79
-
80
- // Import organization
81
- "sort-imports": "off",
82
- "import/order": [
83
- "warn",
84
- {
85
- "groups": [
86
- "builtin",
87
- "external",
88
- "internal",
89
- "parent",
90
- "sibling",
91
- "index",
92
- ],
93
- "pathGroups": [
94
- {
95
- "pattern": "react*",
96
- "group": "external",
97
- "position": "before",
98
- },
99
- ],
100
- "alphabeticalOrder": true,
101
- },
102
- ],
103
71
 
104
72
  // React Query best practices
105
73
  "@tanstack/query/exhaustive-deps": "error",
106
- "@tanstack/query/prefer-query-object-syntax": "warn",
107
- },
108
- "settings": {
109
- "react": {
110
- "version": "detect",
111
- },
112
74
  },
113
75
  "overrides": [
114
76
  {
@@ -126,5 +88,13 @@
126
88
  "@typescript-eslint/no-unused-vars": "off",
127
89
  },
128
90
  },
91
+ {
92
+ // ErrorBoundary sits above ThemeProvider, and colors.ts is the static
93
+ // palette, so both use literal colors on purpose.
94
+ "files": ["src/components/ErrorBoundary.tsx", "src/helper/colors.ts", "src/theme/*Theme.ts"],
95
+ "rules": {
96
+ "react-native/no-color-literals": "off",
97
+ },
98
+ },
129
99
  ],
130
100
  }
@@ -0,0 +1,8 @@
1
+ module.exports = {
2
+ singleQuote: true,
3
+ trailingComma: 'all',
4
+ arrowParens: 'avoid',
5
+ bracketSpacing: true,
6
+ bracketSameLine: true,
7
+ printWidth: 100,
8
+ };
package/template/App.tsx CHANGED
@@ -1,12 +1,12 @@
1
- import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
2
- import { StyleSheet } from "react-native";
3
- import { SafeAreaProvider } from "react-native-safe-area-context";
4
- import { Provider } from "react-redux";
5
- import store, { persistor } from "./src/redux/store";
6
- import { PersistGate } from "redux-persist/integration/react";
7
- import Main from "./Main";
8
- import { ThemeProvider } from "./src/hooks/ThemeContext";
9
- import { ErrorBoundary } from "./src/components/ErrorBoundary";
1
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
2
+ import { SafeAreaProvider } from 'react-native-safe-area-context';
3
+ import { Provider } from 'react-redux';
4
+ import store, { persistor } from './src/redux/store';
5
+ import { PersistGate } from 'redux-persist/integration/react';
6
+ import Main from './Main';
7
+ import { ThemeProvider } from './src/hooks/ThemeContext';
8
+ import { ErrorBoundary } from './src/components/ErrorBoundary';
9
+ import SnackbarHost from './src/components/SnackbarHost';
10
10
 
11
11
  const queryClient = new QueryClient({
12
12
  defaultOptions: {
@@ -27,6 +27,8 @@ function App() {
27
27
  <SafeAreaProvider>
28
28
  <ThemeProvider>
29
29
  <Main />
30
+ {/* Shows messages from showSnackbar / showErrorSnackbar above every screen. */}
31
+ <SnackbarHost />
30
32
  </ThemeProvider>
31
33
  </SafeAreaProvider>
32
34
  </PersistGate>
@@ -36,10 +38,4 @@ function App() {
36
38
  );
37
39
  }
38
40
 
39
- const styles = StyleSheet.create({
40
- container: {
41
- flex: 1,
42
- },
43
- });
44
-
45
41
  export default App;
package/template/Main.tsx CHANGED
@@ -1,11 +1,35 @@
1
- import { NavigationContainer } from "@react-navigation/native";
2
- import React from "react";
3
- import AppStack from "./src/navigation/AppStack";
4
- import { navigationRef } from "./src/helper/navigation-service";
1
+ import React, { useMemo } from 'react';
2
+ import { StatusBar } from 'react-native';
3
+ import { DarkTheme, DefaultTheme, NavigationContainer, type Theme } from '@react-navigation/native';
4
+ import AppStack from './src/navigation/AppStack';
5
+ import { navigationRef } from './src/helper/navigation-service';
6
+ import { useTheme } from './src/hooks/ThemeContext';
5
7
 
6
8
  const Main = () => {
9
+ const { theme, mode } = useTheme();
10
+
11
+ // Gives the native screens and transitions the app's colors, so there's no
12
+ // white flash behind screens in dark mode.
13
+ const navigationTheme = useMemo<Theme>(() => {
14
+ const base = mode === 'dark' ? DarkTheme : DefaultTheme;
15
+ return {
16
+ ...base,
17
+ colors: {
18
+ ...base.colors,
19
+ primary: theme.primary,
20
+ background: theme.background,
21
+ card: theme.card,
22
+ text: theme.text,
23
+ border: theme.border,
24
+ notification: theme.error,
25
+ },
26
+ };
27
+ }, [mode, theme]);
28
+
7
29
  return (
8
- <NavigationContainer ref={navigationRef}>
30
+ <NavigationContainer ref={navigationRef} theme={navigationTheme}>
31
+ {/* Status bar icons follow the active theme (light icons on dark backgrounds). */}
32
+ <StatusBar barStyle={mode === 'dark' ? 'light-content' : 'dark-content'} />
9
33
  <AppStack />
10
34
  </NavigationContainer>
11
35
  );
@@ -1,4 +1,4 @@
1
- const mockStorage = new Map<string, any>();
1
+ const mockStorage = new Map<string, unknown>();
2
2
 
3
3
  export class MMKVMock {
4
4
  set(key: string, value: boolean | string | number | Uint8Array) {
@@ -7,17 +7,17 @@ export class MMKVMock {
7
7
 
8
8
  getString(key: string): string | undefined {
9
9
  const val = mockStorage.get(key);
10
- return typeof val === "string" ? val : undefined;
10
+ return typeof val === 'string' ? val : undefined;
11
11
  }
12
12
 
13
13
  getBoolean(key: string): boolean | undefined {
14
14
  const val = mockStorage.get(key);
15
- return typeof val === "boolean" ? val : undefined;
15
+ return typeof val === 'boolean' ? val : undefined;
16
16
  }
17
17
 
18
18
  getNumber(key: string): number | undefined {
19
19
  const val = mockStorage.get(key);
20
- return typeof val === "number" ? val : undefined;
20
+ return typeof val === 'number' ? val : undefined;
21
21
  }
22
22
 
23
23
  getBuffer(key: string): Uint8Array | undefined {
@@ -7,7 +7,12 @@ import ReactTestRenderer from 'react-test-renderer';
7
7
  import App from '../App';
8
8
 
9
9
  test('renders correctly', async () => {
10
+ let renderer: ReactTestRenderer.ReactTestRenderer | undefined;
10
11
  await ReactTestRenderer.act(() => {
11
- ReactTestRenderer.create(<App />);
12
+ renderer = ReactTestRenderer.create(<App />);
13
+ });
14
+ // Unmount so the splash timer is cleared and Jest can exit.
15
+ await ReactTestRenderer.act(() => {
16
+ renderer?.unmount();
12
17
  });
13
18
  });
@@ -0,0 +1,43 @@
1
+ import {
2
+ cleanPayload,
3
+ formatPrice,
4
+ formatWithComma,
5
+ getErrorMessage,
6
+ } from '../src/helper/common-functions';
7
+ import { pushSnackbar, subscribeSnackbar } from '../src/helper/snackbar';
8
+
9
+ describe('common-functions', () => {
10
+ it('formats numbers', () => {
11
+ expect(formatWithComma(1234567)).toBe('1,234,567');
12
+ expect(formatPrice(1234.5)).toBe('1,234.50');
13
+ });
14
+
15
+ it('removes empty values from payloads', () => {
16
+ expect(cleanPayload({ a: 1, b: '', c: null, d: undefined, e: 0, f: false })).toEqual({
17
+ a: 1,
18
+ e: 0,
19
+ f: false,
20
+ });
21
+ });
22
+
23
+ it('reads error messages from API errors', () => {
24
+ expect(getErrorMessage({ message: 'Invalid token' })).toBe('Invalid token');
25
+ expect(getErrorMessage('Plain')).toBe('Plain');
26
+ });
27
+ });
28
+
29
+ describe('snackbar store', () => {
30
+ it('delivers messages to subscribers until they unsubscribe', () => {
31
+ const listener = jest.fn();
32
+ const unsubscribe = subscribeSnackbar(listener);
33
+
34
+ pushSnackbar('Saved', { type: 'success' });
35
+ expect(listener).toHaveBeenCalledWith(
36
+ expect.objectContaining({ title: 'Saved', type: 'success' }),
37
+ );
38
+
39
+ unsubscribe();
40
+ pushSnackbar('Ignored');
41
+ expect(listener).toHaveBeenCalledTimes(1);
42
+ });
43
+ });