I am using the geolocation API
inside my functional component, and my success
and error
callbacks for geolocation.watchPosition(success, error)
have conditional code that is dependent on some state value that is going to change.
I do not want to initiate geolocation.watchPosition
on mount inside useEffect
.
I tried wrapping the callbacks with useCallback
and passing the state value to the dependency array, but the callback still closes over the stale state value even though it is updated. Is there any workaround to this?
Simplified example:
function Map() {
const watchRef = useRef();
const [isBool, setIsBool] = useState(false);
function init() {
watchRef.current = navigator.geolocation.watchPosition(success, error);
}
const success = useCallback((pos) => {
if(isBool) {
// do something...
return;
}
// do something else...
}, [isBool])
function updateStateHandler() {
setIsBool(true);
}
return // jsx...
}