Skip to content

Instantly share code, notes, and snippets.

@sbkl
Created July 8, 2023 00:40
Show Gist options
  • Save sbkl/a9efcdca96ce0aa289814ff44fb8fc79 to your computer and use it in GitHub Desktop.
Save sbkl/a9efcdca96ce0aa289814ff44fb8fc79 to your computer and use it in GitHub Desktop.
Expo screen orientation "addOrientationChangeListener" bug reporduction
import React from "react";
import * as ScreenOrientation from "expo-screen-orientation";
export type LayoutContextProps = {
currentOrientation: ScreenOrientation.Orientation | undefined;
};
export interface LayoutProviderProps {
children: React.ReactNode;
}
const LayoutContext = React.createContext<LayoutContextProps | undefined>(
undefined,
);
LayoutContext.displayName = "LayoutContext";
export function LayoutProvider({ children }: LayoutProviderProps) {
const [currentOrientation, setCurrentOrientation] = React.useState<
ScreenOrientation.Orientation | undefined
>();
async function initCurrentOrientation() {
if (typeof currentOrientation === "undefined") {
await ScreenOrientation.unlockAsync();
const orientation = await ScreenOrientation.getOrientationAsync();
setCurrentOrientation(orientation);
}
}
React.useEffect(() => {
const screenOrientationListener =
ScreenOrientation.addOrientationChangeListener((event) => {
setCurrentOrientation(event.orientationInfo.orientation);
});
return () => screenOrientationListener.remove();
}, []);
React.useEffect(() => {
initCurrentOrientation();
}, []);
React.useEffect(() => {
console.log({
currentOrientation,
});
}, [currentOrientation]);
return (
<LayoutContext.Provider value={{ currentOrientation }}>
{children}
</LayoutContext.Provider>
);
}
export const useLayout = () => {
const context = React.useContext(LayoutContext);
if (context === undefined) {
throw new Error(`useLayout must be used within a LayoutProvider`);
}
return context;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment