mmkv bug fix

This commit is contained in:
Samandar Turgunboyev
2025-12-11 15:49:53 +05:00
parent c426b729b9
commit fcd704b258
9 changed files with 194 additions and 195 deletions

245
App.tsx
View File

@@ -1,4 +1,5 @@
// App.tsx // App.tsx
import AsyncStorage from '@react-native-async-storage/async-storage';
import { NavigationContainer } from '@react-navigation/native'; import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -7,18 +8,18 @@ import { navigationRef } from 'components/NavigationRef';
import i18n from 'i18n/i18n'; import i18n from 'i18n/i18n';
import React, { useEffect, useMemo, useRef, useState } from 'react'; import React, { useEffect, useMemo, useRef, useState } from 'react';
import { I18nextProvider } from 'react-i18next'; import { I18nextProvider } from 'react-i18next';
import { Animated, Dimensions, LogBox, StatusBar, View } from 'react-native'; import {
Animated,
Dimensions,
LogBox,
StatusBar,
StyleSheet,
View,
} from 'react-native';
import Toast from 'react-native-toast-message'; import Toast from 'react-native-toast-message';
import SplashScreen from './src/components/SplashScreen'; import SplashScreen from './src/components/SplashScreen';
// Screens // Screens
import {
authEvents,
getLanguage,
getToken,
loadInitialAuthData,
storage,
} from 'helpers/event';
import Login from 'screens/auth/login/ui'; import Login from 'screens/auth/login/ui';
import Confirm from 'screens/auth/login/ui/Confirm'; import Confirm from 'screens/auth/login/ui/Confirm';
import Register from 'screens/auth/registeration/ui'; import Register from 'screens/auth/registeration/ui';
@@ -46,81 +47,137 @@ import PaymentQrCode from 'screens/wallet/successPayment/ui/PaymentQrCode';
import Onboarding from 'screens/welcome/Onboarding'; import Onboarding from 'screens/welcome/Onboarding';
LogBox.ignoreLogs([ LogBox.ignoreLogs([
'Non-serializable values were found in the navigation state',
'ViewPropTypes will be removed', 'ViewPropTypes will be removed',
// NOTE: I recommend NOT ignoring "Non-serializable values were found in the navigation state"
// because it hides bugs that can cause crashes. Keep only if you understand the implications.
]); ]);
const Stack = createNativeStackNavigator(); const Stack = createNativeStackNavigator();
const screenWidth = Dimensions.get('window').width; const screenWidth = Dimensions.get('window').width;
const queryClient = new QueryClient(); const queryClient = new QueryClient();
// const saveNotification = async (remoteMessage: any) => {
// try {
// const stored = await AsyncStorage.getItem('notifications');
// const notifications = stored ? JSON.parse(stored) : [];
// const newNotification = {
// id: Date.now(),
// title:
// remoteMessage.notification?.title ||
// remoteMessage.data?.title ||
// 'Yangi bildirishnoma',
// message:
// remoteMessage.notification?.body ||
// remoteMessage.data?.body ||
// 'Matn yoq',
// sentTime: remoteMessage.sentTime || Date.now(),
// };
// await AsyncStorage.setItem(
// 'notifications',
// JSON.stringify([newNotification, ...notifications]),
// );
// } catch (e) {
// console.error('Notification saqlashda xato:', e);
// }
// };
// async function onDisplayNotification(remoteMessage: any) {
// const channelId = await notifee.createChannel({
// id: 'default',
// name: 'Umumiy bildirishnomalar',
// sound: 'default',
// importance: AndroidImportance.HIGH,
// });
// await notifee.displayNotification({
// title:
// remoteMessage.notification?.title ||
// remoteMessage.data?.title ||
// 'Yangi xabar',
// body:
// remoteMessage.notification?.body ||
// remoteMessage.data?.body ||
// 'Matn yoq',
// android: {
// channelId,
// largeIcon: 'ic_launcher_foreground',
// sound: 'default',
// pressAction: {
// id: 'default',
// },
// },
// });
// }
// async function requestNotificationPermission() {
// if (Platform.OS === 'android' && Platform.Version >= 33) {
// const granted = await PermissionsAndroid.request(
// PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
// );
// console.log('POST_NOTIFICATIONS permission:', granted);
// }
// }
export default function App() { export default function App() {
const [initialRoute, setInitialRoute] = useState<string | null>(null); const [initialRoute, setInitialRoute] = useState<string | null>(null);
const slideAnim = useRef(new Animated.Value(0)).current; const slideAnim = useRef(new Animated.Value(0)).current;
const [isSplashVisible, setIsSplashVisible] = useState(true); const [isSplashVisible, setIsSplashVisible] = useState(true);
const isMounted = useRef(false);
const currentAnimation = useRef<Animated.CompositeAnimation | null>(null);
const token = getToken();
useEffect(() => { // useEffect(() => {
loadInitialAuthData(); // requestNotificationPermission();
}, []);
useEffect(() => { // const messagingInstance = getMessaging();
const logoutListener = () => {
if (navigationRef.isReady()) {
navigationRef.reset({
index: 0,
routes: [{ name: 'Login' }],
});
}
};
authEvents.on('logout', logoutListener); // const unsubscribe = onMessage(messagingInstance, async remoteMessage => {
// console.log('Foreground message:', remoteMessage);
// await saveNotification(remoteMessage);
// await onDisplayNotification(remoteMessage);
// });
return () => { // const unsubscribeOpened = onNotificationOpenedApp(
authEvents.removeListener('logout', logoutListener); // messagingInstance,
}; // remoteMessage => {
}, []); // console.log('Backgrounddan ochildi:', remoteMessage);
// saveNotification(remoteMessage);
// },
// );
useEffect(() => { // (async () => {
isMounted.current = true; // const remoteMessage = await getInitialNotification(messagingInstance);
return () => { // if (remoteMessage) {
isMounted.current = false; // console.log('Killeddan ochildi:', remoteMessage);
if (currentAnimation.current) { // saveNotification(remoteMessage);
currentAnimation.current.stop(); // }
} // })();
};
}, []); // return () => {
// unsubscribe();
// unsubscribeOpened();
// };
// }, []);
useEffect(() => { useEffect(() => {
const initializeApp = async () => { const initializeApp = async () => {
try { try {
const seen = storage.getString('hasSeenOnboarding'); const [seen, token, lang] = await Promise.all([
const token = getToken(); AsyncStorage.getItem('hasSeenOnboarding'),
const lang = getLanguage(); AsyncStorage.getItem('token'),
if (lang) { AsyncStorage.getItem('language'),
try { ]);
await i18n.changeLanguage(lang);
} catch (e) { if (lang) await i18n.changeLanguage(lang);
console.warn('i18n.changeLanguage failed:', e);
}
}
const initialRouteName = !seen const initialRouteName = !seen
? 'Onboarding' ? 'Onboarding'
: token : token
? 'Home' ? 'Home'
: 'select-auth'; : 'select-auth';
setInitialRoute(initialRouteName);
if (isMounted.current) {
setInitialRoute(initialRouteName);
}
} catch (error) { } catch (error) {
console.error('App initialization error:', error); console.error('App initialization error:', error);
if (isMounted.current) setInitialRoute('select-auth'); setInitialRoute('select-auth');
} }
}; };
@@ -129,50 +186,52 @@ export default function App() {
const handleSplashFinish = useMemo( const handleSplashFinish = useMemo(
() => () => { () => () => {
// create animation and keep ref so we can stop it on unmount Animated.timing(slideAnim, {
const animation = Animated.timing(slideAnim, {
toValue: -screenWidth, toValue: -screenWidth,
duration: 600, duration: 600,
useNativeDriver: true, useNativeDriver: true,
}); }).start(() => setIsSplashVisible(false));
currentAnimation.current = animation;
animation.start(() => {
// ensure component still mounted before setting state
if (isMounted.current) {
setIsSplashVisible(false);
}
currentAnimation.current = null;
});
}, },
[slideAnim], [slideAnim],
); );
const handleOnboardingFinish = useMemo( const handleOnboardingFinish = useMemo(
() => async (navigation: any) => { () => async (navigation: any) => {
try { await AsyncStorage.setItem('hasSeenOnboarding', 'true');
storage.set('hasSeenOnboarding', 'true');
} catch (e) {
console.warn('Failed to set hasSeenOnboarding', e);
}
navigation.replace('select-auth'); navigation.replace('select-auth');
}, },
[], [],
); );
// const [firebaseToken, setFirebseToken] = useState<{
// fcmToken: string;
// deviceId: string;
// deviceName: string;
// } | null>();
// const app = getApp();
// const messaging = getMessaging(app);
if (!initialRoute || isSplashVisible || !currentAnimation) { // const getDeviceData = async () => {
return ( // try {
<View // const fcmToken = await getToken(messaging);
style={{ // return {
flex: 1, // fcmToken,
justifyContent: 'center', // deviceId: await DeviceInfo.getUniqueId(),
alignItems: 'center', // deviceName: await DeviceInfo.getDeviceName(),
backgroundColor: '#ffff', // };
}} // } catch (e) {
> // console.log('Xato:', e);
<SplashScreen onFinish={handleSplashFinish} /> // return null;
</View> // }
); // };
} // console.log(firebaseToken);
// useEffect(() => {
// getDeviceData().then(data => {
// setFirebseToken(data);
// });
// }, []);
if (!initialRoute) return null;
return ( return (
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
@@ -183,7 +242,7 @@ export default function App() {
<Stack.Navigator <Stack.Navigator
screenOptions={{ screenOptions={{
headerShown: false, headerShown: false,
animation: 'slide_from_right', animation: 'none',
gestureEnabled: false, gestureEnabled: false,
}} }}
initialRouteName={initialRoute} initialRouteName={initialRoute}
@@ -214,6 +273,9 @@ export default function App() {
<Stack.Screen name="PaymentQrCode" component={PaymentQrCode} /> <Stack.Screen name="PaymentQrCode" component={PaymentQrCode} />
<Stack.Screen name="Profile" component={Profile} /> <Stack.Screen name="Profile" component={Profile} />
<Stack.Screen name="Settings" component={Settings} /> <Stack.Screen name="Settings" component={Settings} />
{/* {Platform.OS === 'android' && (
<Stack.Screen name="Notifications" component={Notifications} />
)} */}
<Stack.Screen name="Warehouses" component={Warehouses} /> <Stack.Screen name="Warehouses" component={Warehouses} />
<Stack.Screen name="Support" component={Support} /> <Stack.Screen name="Support" component={Support} />
<Stack.Screen name="ListBranches" component={ListBranches} /> <Stack.Screen name="ListBranches" component={ListBranches} />
@@ -229,6 +291,19 @@ export default function App() {
</Stack.Navigator> </Stack.Navigator>
</NavigationContainer> </NavigationContainer>
{/* Splash transition */}
{isSplashVisible && (
<Animated.View
style={{
...StyleSheet.absoluteFillObject,
transform: [{ translateX: slideAnim }],
zIndex: 10,
}}
>
<SplashScreen onFinish={handleSplashFinish} />
</Animated.View>
)}
<Toast config={toastConfig} /> <Toast config={toastConfig} />
</View> </View>
</I18nextProvider> </I18nextProvider>

13
package-lock.json generated
View File

@@ -37,7 +37,7 @@
"react-native-linear-gradient": "^2.8.3", "react-native-linear-gradient": "^2.8.3",
"react-native-localize": "^3.5.1", "react-native-localize": "^3.5.1",
"react-native-mask-input": "^1.2.3", "react-native-mask-input": "^1.2.3",
"react-native-mmkv": "^4.0.1", "react-native-mmkv": "^2.2.4",
"react-native-modal": "^14.0.0-rc.1", "react-native-modal": "^14.0.0-rc.1",
"react-native-nitro-modules": "^0.31.10", "react-native-nitro-modules": "^0.31.10",
"react-native-push-notification": "^8.1.1", "react-native-push-notification": "^8.1.1",
@@ -13146,14 +13146,13 @@
} }
}, },
"node_modules/react-native-mmkv": { "node_modules/react-native-mmkv": {
"version": "4.0.1", "version": "2.12.2",
"resolved": "https://registry.npmjs.org/react-native-mmkv/-/react-native-mmkv-4.0.1.tgz", "resolved": "https://registry.npmjs.org/react-native-mmkv/-/react-native-mmkv-2.12.2.tgz",
"integrity": "sha512-0JjO0U33b2hngFACsGwxoMCOZlCChP6R42aqvU85kXBaxY/kltSYr0FW9T6lkU3uEkE4IWMV1eLjoJplEY920w==", "integrity": "sha512-6058Aq0p57chPrUutLGe9fYoiDVDNMU2PKV+lLFUJ3GhoHvUrLdsS1PDSCLr00yqzL4WJQ7TTzH+V8cpyrNcfg==",
"license": "MIT", "license": "(MIT AND BSD-3-Clause)",
"peerDependencies": { "peerDependencies": {
"react": "*", "react": "*",
"react-native": "*", "react-native": ">=0.71.0"
"react-native-nitro-modules": "*"
} }
}, },
"node_modules/react-native-modal": { "node_modules/react-native-modal": {

View File

@@ -42,7 +42,7 @@
"react-native-linear-gradient": "^2.8.3", "react-native-linear-gradient": "^2.8.3",
"react-native-localize": "^3.5.1", "react-native-localize": "^3.5.1",
"react-native-mask-input": "^1.2.3", "react-native-mask-input": "^1.2.3",
"react-native-mmkv": "^4.0.1", "react-native-mmkv": "^2.2.4",
"react-native-modal": "^14.0.0-rc.1", "react-native-modal": "^14.0.0-rc.1",
"react-native-nitro-modules": "^0.31.10", "react-native-nitro-modules": "^0.31.10",
"react-native-push-notification": "^8.1.1", "react-native-push-notification": "^8.1.1",

View File

@@ -1,8 +1,6 @@
// axiosInstance import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios'; import axios, { AxiosError } from 'axios';
import { authEvents, getLanguage, getToken, setToken } from 'helpers/event'; import { navigate } from 'components/NavigationRef';
let isLoggingOut = false;
const axiosInstance = axios.create({ const axiosInstance = axios.create({
baseURL: 'https://api.cpcargo.uz/api/v1', baseURL: 'https://api.cpcargo.uz/api/v1',
@@ -12,38 +10,30 @@ const axiosInstance = axios.create({
}, },
}); });
axiosInstance.interceptors.request.use(config => { axiosInstance.interceptors.request.use(async config => {
const token = getToken(); // Tokenni olish
const lang = getLanguage(); const token = await AsyncStorage.getItem('token');
if (token) { if (token) {
config.headers.Authorization = `Bearer ${token}`; config.headers.Authorization = `Bearer ${token}`;
} }
if (lang) { // Languageni olish
config.headers['Accept-Language'] = lang; const language = await AsyncStorage.getItem('language');
if (language) {
config.headers['Accept-Language'] = language;
} }
return config; return config;
}); });
axiosInstance.interceptors.response.use( axiosInstance.interceptors.response.use(
res => res, response => response,
err => { async (error: AxiosError) => {
const status = err.response?.status; if (error.response?.status === 401) {
await AsyncStorage.removeItem('token');
if (status === 401 && !isLoggingOut) { navigate('Login');
isLoggingOut = true;
setToken(null);
authEvents.emit('logout');
setTimeout(() => {
isLoggingOut = false;
}, 500);
} }
return Promise.reject(error);
return Promise.reject(err);
}, },
); );

View File

@@ -1,57 +0,0 @@
// helpers/event.ts
import { EventEmitter } from 'events';
import { createMMKV } from 'react-native-mmkv';
export const authEvents = new EventEmitter();
export const enum AUTH {
USER = 'user',
AUTH = 'auth',
}
// MMKV instance
export const storage = createMMKV();
// Memory cache
let tokenCache: string | null = null;
let languageCache: string | null = null;
// Load on app start (synchronous)
export function loadInitialAuthData() {
tokenCache = storage.getString('token') || null;
languageCache = storage.getString('language') || null;
}
export function getToken() {
return storage.getString('token');
}
export function setToken(token: string | null) {
tokenCache = token;
if (token) {
storage.set('token', token);
} else {
storage.remove('token');
}
}
export function saveAuth() {
storage.set('user', AUTH.USER);
}
export function removeAuth() {
storage.set('user', AUTH.AUTH);
}
export function getAuth() {
storage.getString('user');
}
export function getLanguage() {
return languageCache;
}
export function setLanguage(lang: string) {
languageCache = lang;
storage.set('language', lang);
}

View File

@@ -1,3 +1,4 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native'; import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack'; import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useMutation } from '@tanstack/react-query'; import { useMutation } from '@tanstack/react-query';
@@ -5,7 +6,6 @@ import { authApi } from 'api/auth';
import { otpPayload, resendPayload } from 'api/auth/type'; import { otpPayload, resendPayload } from 'api/auth/type';
import AppText from 'components/AppText'; import AppText from 'components/AppText';
import ErrorNotification from 'components/ErrorNotification'; import ErrorNotification from 'components/ErrorNotification';
import { saveAuth, setToken } from 'helpers/event';
import formatPhone from 'helpers/formatPhone'; import formatPhone from 'helpers/formatPhone';
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -77,12 +77,8 @@ const Confirm = () => {
const { mutate, isPending } = useMutation({ const { mutate, isPending } = useMutation({
mutationFn: (payload: otpPayload) => authApi.verifyOtp(payload), mutationFn: (payload: otpPayload) => authApi.verifyOtp(payload),
onSuccess: async res => { onSuccess: async res => {
setToken(res.data.accessToken); await AsyncStorage.setItem('token', res.data.accessToken);
saveAuth(); navigation.navigate('Home');
navigation.reset({
index: 0,
routes: [{ name: 'Home' }], // login sahifasiga qaytarish
});
setVisible(false); setVisible(false);
}, },
onError: (err: any) => { onError: (err: any) => {

View File

@@ -1,3 +1,4 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
// import { getApp } from '@react-native-firebase/app'; // import { getApp } from '@react-native-firebase/app';
// import { getMessaging, getToken } from '@react-native-firebase/messaging'; // import { getMessaging, getToken } from '@react-native-firebase/messaging';
import { useNavigation } from '@react-navigation/native'; import { useNavigation } from '@react-navigation/native';
@@ -7,7 +8,6 @@ import { authApi } from 'api/auth';
import { otpPayload, resendPayload } from 'api/auth/type'; import { otpPayload, resendPayload } from 'api/auth/type';
import AppText from 'components/AppText'; import AppText from 'components/AppText';
import ErrorNotification from 'components/ErrorNotification'; import ErrorNotification from 'components/ErrorNotification';
import { setToken } from 'helpers/event';
import formatPhone from 'helpers/formatPhone'; import formatPhone from 'helpers/formatPhone';
import React, { useRef, useState } from 'react'; import React, { useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -83,11 +83,8 @@ const Confirm = ({
const { mutate, isPending } = useMutation({ const { mutate, isPending } = useMutation({
mutationFn: (payload: otpPayload) => authApi.verifyOtp(payload), mutationFn: (payload: otpPayload) => authApi.verifyOtp(payload),
onSuccess: async res => { onSuccess: async res => {
setToken(res.data.accessToken); await AsyncStorage.setItem('token', res.data.accessToken);
navigation.reset({ navigation.navigate('Confirm');
index: 0,
routes: [{ name: 'Home' }], // login sahifasiga qaytarish
});
setErrorConfirm(null); setErrorConfirm(null);
}, },
onError: (err: any) => { onError: (err: any) => {

View File

@@ -1,7 +1,7 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native'; import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack'; import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import AppText from 'components/AppText'; import AppText from 'components/AppText';
import { removeAuth, setToken } from 'helpers/event';
import * as React from 'react'; import * as React from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
@@ -36,8 +36,7 @@ const ProfilePages = (props: componentNameProps) => {
style: 'destructive', style: 'destructive',
onPress: async () => { onPress: async () => {
try { try {
setToken(''); await AsyncStorage.removeItem('token');
removeAuth();
navigation.reset({ navigation.reset({
index: 0, index: 0,
routes: [{ name: 'Login' }], // login sahifasiga qaytarish routes: [{ name: 'Login' }], // login sahifasiga qaytarish

View File

@@ -1,5 +1,5 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import AnimatedScreen from 'components/AnimatedScreen'; import AnimatedScreen from 'components/AnimatedScreen';
import { getLanguage, storage } from 'helpers/event';
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import FirstStep from 'screens/welcome/FirstStep'; import FirstStep from 'screens/welcome/FirstStep';
import SecondStep from 'screens/welcome/SecondStep'; import SecondStep from 'screens/welcome/SecondStep';
@@ -17,7 +17,7 @@ const Onboarding = ({ onFinish }: OnboardingProps) => {
useEffect(() => { useEffect(() => {
const loadLang = async () => { const loadLang = async () => {
const savedLang = getLanguage(); const savedLang = await AsyncStorage.getItem('selectedLanguage');
if (savedLang === 'ru' || savedLang === 'uz') { if (savedLang === 'ru' || savedLang === 'uz') {
setLang(savedLang); setLang(savedLang);
setStep(1); setStep(1);
@@ -30,7 +30,7 @@ const Onboarding = ({ onFinish }: OnboardingProps) => {
if (step < 3) { if (step < 3) {
setStep(step + 1); setStep(step + 1);
} else { } else {
storage.set('hasSeenOnboarding', 'true'); await AsyncStorage.setItem('hasSeenOnboarding', 'true');
onFinish(); onFinish();
} }
}, [step, onFinish]); }, [step, onFinish]);