1

I was trying to capture the hight of status bar in react native.

For which I wrote the following code

render() {
    let StatusBarHeight = null
   if (Platform.OS === 'ios') {
     StatusBarHeight = StatusBarManager.getHeight((statusBarHeight)=>{
                console.log(statusBarHeight)
                return statusBarHeight
            })
     console.log(`This is the height of the status bar in iOS:`,StatusBarHeight)
    }
}

Here, the console.log(statusBarHeight) is coming out to be {height: 44} which I intended to store in StatusBarHeight but my second console.log afterwards is giving me undefined

console.log(`This is the height of the status bar in iOS:`,StatusBarHeight)

Which makes me think that StatusBarManager.getHeigh( is async function. So, Can someone help me figure height how can we use async-await in render of react-native

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 1
    I found a similar one : https://stackoverflow.com/questions/49718503/react-native-detect-ios-status-bar-height-when-calling-sharing-hotspot why not detect the height with lifecycles and rerender the UI with setState? – AppleJam Aug 05 '19 at 10:05
  • @AppleJam So appreciate that but I am actually curios to know workarounds of using async in `render() {` – Alwaysblue Aug 05 '19 at 10:06
  • You can also check this - https://stackoverflow.com/questions/50716004/undefined-is-not-an-object-evaluating-statusbarmanager-height-react-native-0-5 – ravibagul91 Aug 05 '19 at 10:12

2 Answers2

2

You should never use async function within the render functions because it blocks your rendering and it should always be responsive and not block your whole app, which would happend if you delay the render function. Save your statusBarHeight within the state and access it in the render function and update it only on external changes (componentDidUdpate e.g.).

The second console.log returns undefined, because render does not wait for the promise (StatusBarManager.getHeight) to resolve and will execute the render function immediately. After the promise is resolved, you see the other console.log with the statusBarHeight. So in essence, no you cannot and should not make render async and save it somewhere else.

Domino987
  • 8,475
  • 2
  • 15
  • 38
0

If you’d like to get the height without listeners, you can do so with the following:

const height = await StatusBarHeight.getAsync();
freedev111
  • 132
  • 4
  • Can you be more specific as to what do you mean? Can you please fit in your example with above code snippet? – Alwaysblue Aug 05 '19 at 10:05