'orientation change listener in expo react native not firing?

i want to detect the current orientation of device in expo react native, this is my code that doesn't work:

import {
 Dimensions,
} from 'react-native';
import * as ScreenOrientation from 'expo-screen-orientation';**
const App = () => {
...
useEffect(() => {
    const isPortrait = () => {
      const dimension = Dimensions.get('screen');
      return dimension.height >= dimension.width;
    };
    Dimensions.addEventListener('change', () => {
      const orientation = isPortrait() ? 'portrait' : 'landscape';
      console.log('Dimensions orientation', orientation);
    });
    ScreenOrientation.addOrientationChangeListener((e) => {
      console.log('e ', e);
    });
  }, []);

how ever when i rotate the device there is no logs so it's not firing?



Solution 1:[1]

This works for me:

const [orientation, setOrientation] = useState(ScreenOrientation.Orientation.PORTRAIT_UP);

useEffect(()=>{
    // set initial orientation
    ScreenOrientation.getOrientationAsync()
    .then((info) =>{
      setOrientation(info.orientation);
    });

    // subscribe to future changes
    const subscription = ScreenOrientation.addOrientationChangeListener((evt)=>{
      setOrientation(evt.orientationInfo.orientation);
    });

    // return a clean up function to unsubscribe from notifications
    return ()=>{
      ScreenOrientation.removeOrientationChangeListener(subscription);
    }
  }, []);

Solution 2:[2]

This is the line that doesn't do anything. Broken, bugged, POS? All of the above?

ScreenOrientation.addOrientationChangeListener((e) => {
 console.log(e);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cabhara
Solution 2 JCraine