React Native Platform OS is not working suddenly

Viewed 1185

I am using Platform.OS to check ios and android. It is working fine, But suddenly it returns me 0 instead of 'ios' or 'android'. After some RND I found that when the app is loading the first time, it returns me 'android' but when I switch the screen and check Platform.OS then it returns me 0 value. I am wondered why it is happening.

I am sharing the console result.

when the app is reloading the first time.

 LOG  Platform.OS
 LOG  android

after that navigate to the other screen and then check Platform OS.

LOG  Platform.OS 
LOG  0

I am sharing the code snippet to check Platform

import { Platform } from 'react-native';

componentDidMount() {
        console.log('Platform.OS');
        console.log(Platform.OS);
}
3 Answers

It looks like you used Platform.OS "=" instead of "==" someplace within the code. Example :

wrong way:

(Platform.OS ='android')?console.log("this the wrong way):console.log('Oops')

right way

(Platform.OS=='android')?console.log("Youpi it works):console.log('in your dream, this gonna happen again')

Same thing happened with me.

I noted that in one place I have check platform condition using single equal operator by mistake like

paddingTop: (Platform.OS = 'android'
                  ? 16
                  : 4)

and then after whenever I have checked platform, I always getting 16.

So make sure if anywhere you have check condition, like Platform.OS = 'android' replace it with Platform.OS == 'android'

As @Rajesh Nasit exposed, I had a similar problem, when I wrote

console.log("Platform.OS:" + Platform.OS) 

I allways was getting in the console "Platform.OS: 100%" And the followed error (in Expo CLient App) => 'Unhandled promised error :Invalid platform was passed "100%" '.

Then after reversed my code and checking all the changes I've made, I found the line what was the responsible for thar error.

I had in my StyleSheet the following line

width: Platform.OS === 'android' ? "100%" : "100%",

I asume React-Native somehow set the value "100%" to the Platform.OS.

At final, I resolved that error as follow:

const styles = StyleSheet.create({
imagebackground: {
          ...Platform.select({
            ios: {
              width: "100%",
            },
            android: {
              width: "100%",
            },
            default: { 
              width: "100%",
            }
          }),
          marginLeft: 0,
        },

Well I hope someone find this answer usefull.

Related