import AsyncStorage from '@react-native-community/async-storage' ; import { findBestAvailableLanguage } from 'react-native-localize' ; import noop from 'lodash/noop' ; import { defaultLanguage , languagesResources } from './languageConfig' ; const LOCALE_PERSISTENCE_KEY = 'app_locale' ; const RNLanguageDetector = { type : 'languageDetector' , async : true , detect : async ( cb ) : Promise < void > => { try { const persistedLocale = await AsyncStorage . getItem ( LOCALE_PERSISTENCE_KEY ) ; if ( ! persistedLocale ) { const languageTags = Object . keys ( languagesResources ) ; const detectedLocale = await findBestAvailableLanguage ( languageTags ) ; return cb ( detectedLocale ?. languageTag ?? defaultLanguage ) ; } cb ( persistedLocale ) ; } catch { console . warn ( 'Failed to detect locale!' ) ; console . warn ( 'Will use defaultLanguage:' , defaultLanguage ) ; cb ( defaultLanguage ) ; } } , init : noop , cacheUserLanguage : ( locale ) : void => { AsyncStorage . setItem ( LOCALE_PERSISTENCE_KEY , locale ) ; } , } ; export default RNLanguageDetector ;