Skip to content

Commit

Permalink
feat(usegeolocated): add support to watch location permission change
Browse files Browse the repository at this point in the history
  • Loading branch information
mfaheemakhtar committed Apr 29, 2023
1 parent 474f6cd commit ca1fdd2
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ export interface GeolocatedConfig {
* @default true
*/
isOptimisticGeolocationEnabled?: boolean;
/**
* If set to true, the component watches for location permission changes.
* @default false
*/
watchLocationPermissionChange?: boolean;
/**
* Callback to call when geolocation API invocation fails. Called with undefined when the user decision times out.
*/
Expand Down Expand Up @@ -91,6 +96,7 @@ export function useGeolocated(config: GeolocatedConfig = {}): GeolocatedResult {
geolocationProvider = typeof navigator !== "undefined"
? navigator.geolocation
: undefined,
watchLocationPermissionChange = false,
onError,
onSuccess,
} = config;
Expand All @@ -108,6 +114,9 @@ export function useGeolocated(config: GeolocatedConfig = {}): GeolocatedResult {
const [positionError, setPositionError] = useState<
GeolocationPositionError | undefined
>();
const [permissionState, setPermissionState] = useState<
PermissionState | undefined
>();

const cancelUserDecisionTimeout = useCallback(() => {
if (userDecisionTimeoutId.current) {
Expand Down Expand Up @@ -177,6 +186,31 @@ export function useGeolocated(config: GeolocatedConfig = {}): GeolocatedResult {
positionOptions,
]);

useEffect(() => {
let permission: PermissionStatus;

if (
watchLocationPermissionChange &&
geolocationProvider &&
"permissions" in navigator
) {
navigator.permissions
.query({ name: "geolocation" })
.then((result) => {
permission = result;
permission.onchange = () => {
setPermissionState(permission.state);
};
});
}

return () => {
if (permission) {
permission.onchange = null;
}
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps

useEffect(() => {
if (!suppressLocationOnMount) {
getPosition();
Expand All @@ -188,7 +222,7 @@ export function useGeolocated(config: GeolocatedConfig = {}): GeolocatedResult {
geolocationProvider?.clearWatch(watchId.current);
}
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}, [permissionState]); // eslint-disable-line react-hooks/exhaustive-deps

return {
getPosition,
Expand Down

0 comments on commit ca1fdd2

Please sign in to comment.