Is there a way to re-run the hook when the Location Permission changes on the browser?
Just want to ask if there's a way to re-run the useGeolocated hook when the Location Permission changes on the browser. Does the library already do this?
My Code
import { useGeolocated } from "react-geolocated";
import useComponentHasMounted from "@/hooks/useComponentHasMounted";
const Home: NextPage = () => {
const { coords, isGeolocationAvailable, isGeolocationEnabled } =
useGeolocated({
positionOptions: {
enableHighAccuracy: false,
},
userDecisionTimeout: 5000,
watchPosition: true,
});
// Custom hook for checking if component is mounted.
// Prevents hydration mismatch bug with NextJS
const hasMounted = useComponentHasMounted();
return (
<>
{hasMounted && (
<>
{!isGeolocationAvailable && "Your device can't use Geolocation."}
{isGeolocationAvailable && isGeolocationEnabled
? `Showing coords: ${coords?.latitude}, ${coords?.longitude}`
: "Your device can use Geolocation, but it's not enabled."}
</>
)}
</>
);
};
Output
Although, I'm looking for a way that the hook just runs again without refreshing. In other words, running another geolocation query when the Location permission changes.

Possible Solutions
- My possible solution is adding an event listener to the PermissionsAPI change event and using that to re-render the component that uses the
useGeolocatedhook. - Another solution is adding the
getPosition()callback to the same 'change' event. Does this affect the values returned by the hook? - Another solution could also be adding this to the library by adding an optional configuration parameter to the hook. Like so:
useGeolocated({ requeryOnLocationPermissionChange: true; });
Just made this issue to mainly ask a question though... if the library already does this. What would you recommend?
Hi, thanks for the detailed question :) the library does not react to the changes to the permissions so I would recommend using the permissions API as you suggest and in the reaction to the change you could call the getPosition callback you get from the useGeolocated to trigger the hooks internal logic again (the same as if you re-rendered the component, I hust think, this is cleaner).
As for the addition, it is a nice suggestion, if you are interested in making a PR for it, it would be most appreciated :)
@no23reason, I guess I can make a PR if this feature still interests anyone.
@no23reason , this was stale on my machine for months. I was just cleaning my folder and found I have not pushed this incomplete work yet.
I have added an effect to watch permission change and it worked as expected.
I was not able to write a test correctly because something was not working as expected. My test is not correct. Or the code has some side effects.
Unfortunately, I can't complete this PR.
Thanks to @Blankeos for the explanation in the issue.
:tada: This issue has been resolved in version 4.1.0 :tada:
The release is available on:
Your semantic-release bot :package::rocket: