Home > other >  useEffect can't update the state
useEffect can't update the state

Time:10-27

I have a part of code that loads the stored language of i18n. I am trying to get the language, change the state to true and then show the page on screen.

The code doesn't update the "yesLanguage" state and it still return false..

The code must return TRUE "yesLanguage".

The goal of the code is to set default language of application before showing the screen then showing the screen with a default language (language the the user recently set).

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */
/*
 import React from 'react';
 import {Text} from 'react-native';

  //import {SignUpScreen} from './src/components/PlayAround/ResponsiveLayout';
  import {HomeScreen} from './src/screens/HomeScreen';
 
 
  function App (props){
    return(
      <HomeScreen />
    );
  }
  
  
  
  export default App;
  */

import React,{useState,useEffect} from 'react';
import  './translations/i18n';
import {View, Text,Pressable} from 'react-native';
import {useTranslation} from 'react-i18next';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {HomeScreen} from './src/screens/HomeScreen';
import 'intl-pluralrules';



function App(props){


const {t, i18n} = useTranslation();
const [currentLanguage,setLanguage] = useState('ar');
const [yesLanguage , setYesLanguage] = useState(false);





const changeLanguage = value => {
    
    
    i18n
    .changeLanguage(value)
    .then(() => setLanguage(value))
    .catch(err => console.log(err));
    AsyncStorage.setItem('currentLnaguage',value);
    
};


React.useEffect(()=>{
    AsyncStorage.getItem('currentLnaguage').then(val => {
        
        //console.log(val 'useeee2');
        let newDefaultLang = val ? val :"ar"; // or Change ar with the default language
        i18n.locale = newDefaultLang;
        changeLanguage(newDefaultLang);
        //
        setYesLanguage(true);
        console.log(newDefaultLang "qqqq");
    });
    
},[]);

console.log(yesLanguage);
//AsyncStorage.clear();
return yesLanguage && <HomeScreen buttonTitle={t('ordernow')} deliveryText={t('delivery')} />

};

export default App;


update here is my i18n file code

import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
//import LanguageDetector from 'i18next-browser-languagedetector';
import en from './en/en.json';
import ar from './ar/ar.json';
import he from './he/he.json';
import AsyncStorage from '@react-native-async-storage/async-storage';
import React from 'react';


/*
i18n
.use(initReactI18next).init({
  lng: 'en',
  fallbackLng: 'en',
  resources: {
    en: en,
    ar: ar,
  },
  interpolation: {
    escapeValue: false // react already safes from xss
  }
});*/


const getDefaultLang = async () => {

  
  
  const storedLang = await AsyncStorage.getItem('currentLnaguage');
  
  
  /*if(storedLang!= null){
    i18n.defaultLocale = storedLang;
    i18n.locale = storedLang;
    i18n.fallbacks = true;
  }*/

  

  return i18n
    .use(initReactI18next) 
    .init({
      resources: {
        en: en,
        ar: ar,
        he: he
      },
      lng: storedLang ? storedLang : 'ar', 
      //lng: storedLang || "ar",
      interpolation: {
        escapeValue: false, 
      },

      fallbackLng: ['en', 'ar','he'],
    });
};

export default getDefaultLang();

CodePudding user response:

If useEffect doesn't work fun, just use the useFocusEffect

import { useFocusEffect } from '@react-navigation/native';

useFocusEffect(
        React.useCallback(() => {
            // your code here
        }, [])
    );

CodePudding user response:

There are some useEffect dependecy changes needs to be done and it will work like a charm.

Have a look at the below code with changes and let me know if it works.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React,{useState,useEffect} from 'react';
import  './translations/i18n';
import {useTranslation} from 'react-i18next';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {HomeScreen} from './src/screens/HomeScreen';
import 'intl-pluralrules';

function App(props){

    const {t, i18n} = useTranslation();
    const [currentLanguage,setLanguage] = useState('ar');
    const [yesLanguage , setYesLanguage] = useState(false);

    const changeLanguage = React.useCallback(async value => {
        i18n
        .changeLanguage(value)
        .then(() => setLanguage(value))
        .catch(err => console.log(err));
        await AsyncStorage.setItem('currentLnaguage',value);
    }, []);

    React.useEffect(()=>{
        AsyncStorage
        .getItem('currentLnaguage')
        .then(val => {
            let newDefaultLang = val ? val :"ar"; // or Change ar with the default language
            i18n.locale = newDefaultLang;
            changeLanguage(newDefaultLang);
            setYesLanguage(true);
            console.log(newDefaultLang "qqqq");
        });
    },[changeLanguage]);

    console.log(yesLanguage);
    return yesLanguage && <HomeScreen buttonTitle={t('ordernow')} deliveryText={t('delivery')} />
};

export default App;
  • Related