Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

Showing posts with label expo. Show all posts
Showing posts with label expo. Show all posts

February 16, 2025

Centralized Loading and Error Handling in React Native with Middleware and Zustand

February 16, 2025 Posted by Mehedi Hassan Piash , , , , No comments

 Managing loading states and handling errors efficiently is crucial for creating a smooth user experience in React Native applications. In this blog, we will explore how to centralize loading state management using Redux Toolkit Query (RTK Query) and middleware, while leveraging Zustand for error handling.

Centralized Loading Management with RTK Query

1. Centralized Loading Management with RTK Query

RTK Query simplifies API state management by handling caching, invalidation, and background fetching. We can centralize the loading state by selecting the active API requests using a global selector.

Defining a Global Loading Selector

import { createSelector } from '@reduxjs/toolkit';
import { movieApi } from '../../src/redux/query/RTKQuery.ts';
const selectGlobalLoading = createSelector(
(state: any) => state[movieApi.reducerPath],
(apiState) => {
const isFetchingQueries = Object.values(apiState.queries).some(
(query: any) => query?.status === 'pending'
);
const isFetchingMutations = Object.values(apiState.mutations).some(
(mutation: any) => mutation?.status === 'pending'
);
return isFetchingQueries || isFetchingMutations;
}
);
export { selectGlobalLoading };

This selector scans all active API queries and mutations, checking if any are still in a “pending” state.

Creating a Global Loading Spinner

To display a loading indicator whenever an API call is in progress, we use the useSelector hook.

import React from 'react';
import { ActivityIndicator, View } from 'react-native';
import styles from './LoadingSpinner.style.ts';
import { useSelector } from 'react-redux';
import { selectGlobalLoading } from '../../utils/Common.ts';
import { colors } from '../../constant/Colors.ts';
const LoadingSpinner = () => {
const isLoading = useSelector(selectGlobalLoading);
if (!isLoading) return null;
return (
<View style={styles.container}>
<ActivityIndicator size={'large'} color={colors.primaryColor} />
</View>
);
};
export default LoadingSpinner;

This component listens for loading state updates and displays an overlay with an ActivityIndicator when an API request is in progress.

Adding the Loading Spinner to the App

We integrate the LoadingSpinner component into the main application layout:

<SafeAreaProvider>
<Navigation />
<NetworkConnection />
<LoadingSpinner />
</SafeAreaProvider>

This ensures that the loading indicator is always accessible at the root level of the app.

2. Centralized Error Handling Using Middleware and Zustand

Instead of manually handling API errors in each component, we can use Redux middleware to capture errors globally and manage them using Zustand.

Defining Zustand Store for Error Handling

Zustand is a lightweight state management library that provides a simple API for managing global state.

import { create } from 'zustand';
interface ErrorState {
visible: boolean;
message: string;
showError: (message: string) => void;
hideError: () => void;
}
export const useApiErrorStore = create<ErrorState>((set) => ({
visible: false,
message: '',
showError: (message: string) => set({ visible: true, message }),
hideError: () => set({ visible: false, message: '' }),
}));

This store exposes methods to show and hide error messages globally.

Creating an RTK Middleware for Error Handling

Middleware allows us to intercept Redux actions and handle errors in a centralized way.

import { isRejectedWithValue, Middleware } from '@reduxjs/toolkit';
import { useApiErrorStore } from '../zustand-store/ApiErrorStore.ts';
interface ErrorResponse {
status: number;
data: {
message?: string;
error?: string;
};
}
export const rtkQueryErrorMiddleware: Middleware = () => (next) => (action) => {
if (isRejectedWithValue(action)) {
const error = action.payload as ErrorResponse;
const errorMessage =
error.data?.message ||
error.data?.error ||
'Something went wrong. Please try again.';
if (errorMessage !== 'Invalid token')
useApiErrorStore.getState().showError(errorMessage);
}
return next(action);
};

This middleware listens for rejected API requests and automatically updates the Zustand store with the error message.

Integrating Middleware in Redux Store Configuration

We add the error-handling middleware to the Redux store:

import { configureStore } from '@reduxjs/toolkit';
import logger from 'redux-logger';
import { movieApi } from './query/RTKQuery.ts';
import { setupListeners } from '@reduxjs/toolkit/query';
import { rtkQueryErrorMiddleware } from './RtkQueryErrorMiddleware.ts';
const configureAppStore = () => {
const store = configureStore({
reducer: {
[movieApi.reducerPath]: movieApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat([
logger,
rtkQueryErrorMiddleware,
movieApi.middleware,
]),
devTools: process.env.NODE_ENV === 'development',
});
setupListeners(store.dispatch);
return store;
};
export default configureAppStore;

This ensures that API errors are caught and processed before they reach UI components.

Conclusion

By implementing a centralized loading state using RTK Query and Redux, combined with middleware-driven error handling and Zustand, we have built a robust foundation for managing API state in a React Native app. This approach improves maintainability and ensures a smoother user experience by automatically handling loading indicators and displaying error messages globally.

GitHub: https://github.com/piashcse/react-native-movie
Medium: https://piashcse.medium.com/centralized-loading-and-error-handling-in-react-native-with-middleware-and-zustand-683efd02b792

December 19, 2024

Localization in React Native

December 19, 2024 Posted by Mehedi Hassan Piash , , 1 comment

 Localization is essential for making your React Native app accessible to a global audience. By supporting multiple languages, you ensure users from different regions have a seamless experience. Let’s start step by step.

Multiple language support

Step 1: Install Required Libraries

npm install i18next react-i18next react-native-localize

Step 2: Create Translation Files

Store translations in JSON files for each language. For example:
en.json (English):

{
"welcome": "Welcome",
"greeting": "Hello, {{name}}!"
}

bn.json (Bangali):

{
"welcome": "স্বাগতম",
"greeting": "হ্যালো, {{name}}!"
}

Step 3: Initialize i18next

import i18n from 'i18next';
import en from './locale-json/en.json';
import bn from './locale-json/bn.json';
import { initReactI18next } from 'react-i18next';
import { getLocales } from 'react-native-localize';

// Define the type for supported languages
export type TranslationKeys = keyof typeof en;

// Detect the device language
const getDeviceLanguage = (): string => {
const locales = getLocales();
return locales[0]?.languageTag || 'en';
};

// Initialize i18next
i18n.use(initReactI18next).init({
compatibilityJSON: 'v4',
resources: {
en: { translation: en },
bn: { translation: bn },
},
lng: getDeviceLanguage(),
fallbackLng: 'en',
interpolation: {
escapeValue: false,
},
});

export const i18nLocale = i18n;

Step 4: Wrap your app.js with the provider

import { I18nextProvider } from 'react-i18next';
import i18n from 'i18next';

const App = () => {
return (
<Provider store={store}>
<PaperProvider>
<I18nextProvider i18n={i18n}>
<SafeAreaProvider>
<Navigation />
</SafeAreaProvider>
</I18nextProvider>
</PaperProvider>
</Provider>
);
};

Step 5: Make a hook to make it more useful

import { useMemo } from 'react';
import { i18nLocale } from '../locale/i18nLocale.ts';
import { AppString } from '../locale/AppString.ts';

type AppStringKey = keyof typeof AppString; // Keys of APP_STRING

export const useLocalization = () => {
return useMemo(() => {
const localizedStrings: Record<AppStringKey, string> = {} as Record<
AppStringKey,
string
>;

(Object.keys(AppString) as AppStringKey[]).forEach((key) => {
localizedStrings[key] = i18nLocale.t(AppString[key]);
});

return localizedStrings;
}, []);
};
export const AppString = {
WELCOME: 'Welcome',
GEETINGS: "Hello, {{name}}!"
}

Step 6: Use it in your component

const App = () => {
const localization = useLocalization();

return (
<View>
<Text>{localization.WELCOME}</Text>
</View>
);
};

export default App;

Ref:
GitHub: https://github.com/piashcse/react-native-movie
Medium: https://piashcse.medium.com/localization-in-react-native-a2a48e45cd27

October 20, 2024

ESLint and Prettier configuration for React-Native and Expo

October 20, 2024 Posted by Mehedi Hassan Piash , , , , No comments

 Setting up ESLint and Prettier in your React Native or Expo project is essential for maintaining consistent code quality and style. ESLint helps identify and fix problematic code patterns, while Prettier ensures your code is formatted consistently across the entire team. In this guide, we’ll walk through configuring ESLint and Prettier for a React Native/Expo project step-by-step.

Step 1: Create a New React Native or Expo Project

npx react-native init expo-museum 
npx create-expo-app expo-museum

Navigate to your project directory:

cd expo-museum

Step 2: Install ESLint and Prettier
Remove the previous ESLint configuration:

npm uninstall @react-native-community/eslint-config eslint

Add ESLint and Prettier as development dependencies:

npm install eslint prettier --save-dev

Additionally, you’ll need some ESLint plugins for React Native and Prettier integration:

npm install eslint-config-prettier eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-native - save-dev

Step 3: Initialize ESLint
Run the following command to initialize ESLint and generate a configuration file:

npx eslint - init

Follow the prompts as outlined below:

Step 4: Add ESLint configuration
Add the given configuration to the newly created eslint.config.js

import globals from 'globals';
import pluginJs from '@eslint/js';
import tseslint from 'typescript-eslint';
import pluginReact from 'eslint-plugin-react';
import prettierConfig from 'eslint-config-prettier';
import prettierPlugin from 'eslint-plugin-prettier';

export default [
{ files: ['**/*.{js,mjs,cjs,ts,jsx,tsx}'] },
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
pluginReact.configs.flat.recommended,
prettierConfig, // Disables conflicting ESLint rules with Prettier
{
ignores: ['node_modules/', 'android/', 'ios/', 'build/'],
plugins: { prettier: prettierPlugin }, // Register the Prettier plugin
rules: {
'react/react-in-jsx-scope': 'off',
'no-unused-vars': 'warn',
'react-native/no-inline-styles': 'off',
'prettier/prettier': 'error', // Enforce Prettier rules
},
settings: {
react: {
version: 'detect', // Automatically detect React version
},
},
},
];

Step 5: Create Prettier Configuration
Create a .prettierrc file in the root of your project:

{
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80,
"tabWidth": 2,
"bracketSpacing": true,
"jsxBracketSameLine": false,
"useTabs": false
}

Create a .prettierignore file in the root of your project:

node_modules/
android/
ios/
build/

Step 6: Add Scripts for ESLint and Prettier
Update your package.json with scripts to run ESLint and Prettier:

"lint": "npx eslint .",
"lintFixAll": "npx eslint '**/*.{js,jsx,ts,tsx}' --fix",
"prettierFixAll": "npx prettier --write '**/*.{js,jsx,ts,tsx,json,md}'",
"fix:lintPrettier": "npm run prettierFixAll && npm run lintFixAll"

Step 7: Test your configuration by running the script in your terminal

npm run lint 
npm run lintFixAll
npm run prettierFixAll
npm run fix:lintPrettier

Here is the result you will get and change your configuration according to your needs 🙂 Happy coding.

GitHub Link: https://github.com/piashcse/expo-museum
Medium: https://piashcse.medium.com/eslint-and-prettier-configuration-for-react-native-and-expo-cbe333bd3421