getCurrentPosition in the React Native geolocation API is only running 10% of the time? - react-native

I am running the React Native getCurrentPosition Geolocation function within componentDidMount like this:
async componentDidMount(){
alert('comp mounting');
await navigator.geolocation.getCurrentPosition(
(position) => {
alert("state of lat in callback is "+position.coords.latitude);
this.setState({lat: position.coords.latitude, long: position.coords.longitude});
},
(error) => {alert("there was an error getting location")},
{enableHighAccuracy: true}
);
}
It alerted the latitude the first time I ran it, and maybe a couple other times out of about 40 tries. I think all of those runs were without async and await. About 90% of the time neither the alert within the success callback nor the alert in the error callback run.
I put async and await in because I figured the request was taking too long (ran immediately the first time though).
I need to pass location information to a child component.
Is the React Native default Geolocation library just not very good or am I doing something wrong? Should I switch to using the seperate iOS/Android geolocation options?

The alert() calls appear to be the problem. Once I removed the alert() calls it started working.

Related

Abort an Updates.fetchUpdateAsync() after a certain time [Expo/React native]

Expo React Native SDK Version: 46
Platforms: Android/iOS
Package concerned : Expo.Updates
Hello everyone, I want to programmatically check for new updates, without using the fallbackToCacheTimeout in app.json that will trigger the check of the new updates when the application is launched because like that I can't put a custom loading page.
So by doing this all by code as follow :
try{
const update = await Updates.checkForUpdateAsync();
if(update.isAvailable){
await Updates.fetchUpdateAsync();
await Updates.reloadAsync();
}else{}
}catch(err){}
But I want to be able to abort all those calls after a certain time (thus, the user that have a bad connection can use the app without waiting a very long time).
I check the documentation and I cannot found any method that allow this.
I dont't think it's possible to cancel a Promise for now in Javascript, or maybe any connection ?
Or does the "fallbackToCacheTimeout" value in the app.json will automatically apply to the fetch updates call of the Expo API?
Do someone have any idea how to do it ? :(
First of all I am assuming you have set updates.checkautomatically field to ON_ERROR_RECOVERY in app.json or app.config.js file. If not, please check the documentation. The reason why you need this is to avoid automatic updates which can also block your app on splash screen.
Updated Solution
Because of the limitation in javascript we can't cancel any external Promise (not created by us or when its reject method is not exposed to us). Also the function fetchUpdateAsync exposed to us is not a promise but rather contains fetch promise and returns its result.
So, here we have two options:
Cancel reloading the app to update after a timeout.
But note that updates will be fetched in background and stored on
the device. Next time whenever user restarts the app, update will
be installed. I think this is just fine as this approach doesn't
block anything for user and also there is a default timeout for http
request clients like fetch and axios so, request will error out in
case of poor/no internet connection.
Here is the code:
try {
const update = await Updates.checkForUpdateAsync();
if (update.isAvailable) {
const updateFetchPromise = Updates.fetchUpdateAsync();
const timeoutInMillis = 10000; // 10 seconds
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject("timedout"), timeoutInMillis))
// This will return only one Promise
Promise.race([updateFetchPromise, timeoutPromise])
.then(() => Updates.reloadAsync())
.catch((error) => {
if (error === 'timedout') {
// Here you can show some toast as well
console.log("Updates were not cancelled but reload is stopped.")
} else if (error === 'someKnownError') {
// Handle error
} else {
// Log error and/or show a toast message
}
})
} else {
// Perform some action when update is not available
}
} catch (err) {
// Handle error
}
Change the expo-updates package just for your app using a patch
Here you can return a cancel method with Updates.fetchUpdateAsync() and use it with setTimeout to cancel the fetch request. I won't be providing any code for this part but if you are curious I can definitely provide some help.
Please refer this section to understand use of fallbackToCacheTimeout in eas updates.
Old solution:
Now, for aborting or bypassing the promise i.e. Updates.fetchUpdateAsync in your case. You can basically throw an Error in setTimeout after whatever time duration you want, so that, catch block will be executed, bypassing the promises.
Here is the old code :
try{
const update = await Updates.checkForUpdateAsync();
if(update.isAvailable){
// Throw error after 10 seconds.
const timeout = setTimeout(() => { throw Error("Unable to fetch updates. Skipping..") }, 10000)
await Updates.fetchUpdateAsync();
// Just cancel the above timeout so, no error is thrown.
clearTimeout(timeout)
await Updates.reloadAsync();
}else{}
}catch(err){}

How to use setTimeout in react native?

Hi I working on a react native project I need to support my app offline.
I used NetInfo Library from expo documentation.
like below
const netInfo = useNetInfo();
const networkCheck = () => {
setTimeout(() => {
const net = netInfo.isInternetReachable;
console.log(net);
if (net === false) {
setloadCachedListings(true);
}
}, 2000);
};
networkCheck();
I want to wait for some time at this step of my code because this hook always returns null first time then after few milliseconds it tells the real network status.
But this code is not working as I an trying to do.
Is there any way to achieve this?
I just want to wait a little bit to get real network connection and then go further with my code.
logs for netInfo hook.

React Native fetch API error - page keeps refreshing

I'm trying to fetch this api into my android app. However, the emulator screen keeps loading. Can somebody please point out the error?
Check code
componentDidMount is returning without handling the Promise.
You don't have to return anything in componentDidMount anyway. So you can just have
componentDidMount() {
fetch(...).then(res => res.json()).then((jsonRes) => {})
}
Or use async/await

Dispatch an action in background app refresh with react native

I'm using react-native-background-fetch to receive app refresh events and have been struggling to dispatch an action (that fetches data) when it's triggered. I'm able to do this outside of redux but not when I dispatch the action.
BackgroundFetch.configure({
stopOnTerminate: false
}, async () => {
await store.dispatch(getItemsAction);
BackgroundFetch.finish();
});
Action:
export function getItemsAction() {
// <-- Reaches here
return async (dispatch, getState) => {
// <-- But not here
const items = await findAll();
dispatch(itemsRetrieved(items));
}
}
If not a solution, I'd like to get some insight into what's happening here.
First of all you need to call action creator
await store.dispatch(getItemsAction());
Then you'll need a middleware to handle functions as actions. I assume you are aware of redux-thunk.
If it's a headless task running in the background, It does not have access to the redux store from what I experienced.
You will want to use something like AsyncStorage (https://github.com/react-native-community/async-storage) when running the task as headless js, which is what happens when the app is running background events.

AsyncStorage is not returning the callback

I am using redux-persist in a react native project, that runs just fine in a broad number of devices except Android 7. I am trying to debug the problem on why my local storage is nor persisting and found this:
The following code executes inside React Native component lifecycle's
componentDidMount() {
attachObservables(store)
setInterval(async () => {
console.log('Inside setInterval')
const data = await AsyncStorage.getAllKeys()
console.log('inside the getAllKeys')
data.forEach(async k => {
const value = await AsyncStorage.getItem(k)
console.group(k)
console.log(value)
console.groupEnd()
})
}, 3000)
}
Code after 'Inside setInterval' is never called. It only runs once if outside the setInterval. If I call once the code outside the setInterval it appears to run just fine. I also tried callback format vs async / await version but it does not seem to matter.
Same problem I had using firebase js library (callbacks never return after the first one). I am now looking for alternatives to workaround the problem.
Any ideas?
As of React Native 0.51 in some Android versions, the runtime can get blocked by other native modules, impeding the resolution of the mentioned methods.
It can be fixed via https://github.com/facebook/react-native/issues/14101#issuecomment-345563563, ensuring this methods use a free thread from the thread pool.
A PR has been submitted and I hope that will be released in future versions. If you want it to use this fix right now, it is available here https://github.com/netbeast/react-native
EDIT:
I am not experiencing this anymore on real devices over react-native#0.53, anyhow others have also reported, so the issue is still open.