Home > Software engineering >  Changing a state of a variable in a function
Changing a state of a variable in a function

Time:06-09

I have two fonts one if the app is in arabic and one if the app is in English. My thinking is declare the state at the top but when the user changes the font it reverts the false state.

const App = ({navigation}) => {
  const [newFont, setNewFont] = useState();
  i18n.on('languageChanged', () => {
    console.log('languageChanged');
    setNewFont(true);
  });

  const customTextProps = {
    style: {
      fontFamily: Fonts.GLOBAL_APP_FONT,
    },
  };
  const customTextInputProps = {
    style: {
      fontFamily: Fonts.GLOBAL_APP_FONT,
    },
  };
  setCustomText(customTextProps);
  setCustomTextInput(customTextInputProps);
  const arabictextProps = {
    style: {
      fontFamily: Fonts.GLOBAL_APP_ARABIC_FONT,
    },
  };

  if (newFont === true) {
    setCustomText(arabictextProps);
    setCustomTextInput(arabictextProps);
    console.log('fontChange', newFont);
  } else {
    console.log('fontChange', newFont);
    setCustomText(customTextProps);
    setCustomTextInput(customTextProps);
  }

The state is declared true when the user triggers the i18 .on function, but the app refreshes and changes the state again.

Please help me figure a way to change the state...

CodePudding user response:

You should not change the state inside the function because it causes a loop: every time you update the state the function is called back.

Try with the below example where the state will only change when the languageChanged is called:

const customTextProps = {
    style: {
        fontFamily: Fonts.GLOBAL_APP_FONT
    }
}
const customTextInputProps = {
    style: {
        fontFamily: Fonts.GLOBAL_APP_FONT
    }
}

const arabictextProps = {
    style: {
        fontFamily: Fonts.GLOBAL_APP_ARABIC_FONT
    }
}

const App = ({ navigation }) => {
    const [customText, setCustomText] = useState(customTextProps)
    const [customTextInput, setCustomTextInput] = useState(customTextInputProps)

    useEffect(() => {
        i18n.on('languageChanged', () => {
            console.log('languageChanged')

            setCustomText(arabictextProps)
            setCustomTextInput(arabictextProps)
        })
    }, [])
}

CodePudding user response:

  const customTextProps = {
    style: {
      fontFamily: Fonts.GLOBAL_APP_FONT,
    },
  };
  const customTextInputProps = {
    style: {
      fontFamily: Fonts.GLOBAL_APP_FONT,
    },
  };
  setCustomText(customTextProps);
  setCustomTextInput(customTextInputProps);
  const arabictextProps = {
    style: {
      fontFamily: Fonts.GLOBAL_APP_ARABIC_FONT,
    },
  };

  if (i18n.language === 'ar') {
    setCustomText(arabictextProps);
    setCustomTextInput(arabictextProps);
  } else {
    setCustomText(customTextProps);
    setCustomTextInput(customTextProps);
  }

All I needed to do was change the if statement to check if the app is in Arabic.

  • Related