React Native fetch API error - page keeps refreshing - api

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

Related

React Native Linking eventListener crashes with deep linking

I am trying to implement deep linking/universal linking with my React Native app and it works good so far, but one thing. I have an eventListener and getInitialUrl in my app.js like so:
useEffect(() => {
Linking.addEventListener("url", (url) => handleInvite(url));
Linking.getInitialURL().then((url) => handleInvite(url));
}, []);
getInitialUrl works fine and the app opens and gets the url. This function is when the app is not active in the background. However, when the app is in the background the eventListener gets fired and the app crashes immediately. I tested it with and without and the problem is the eventListener, but I don't know why.
The app crashes immediately and I can't find any info on this problem. So any help would be much appreciated.
This is tested on iOS.
So I found the problem. Basically the addEventListener returns an array and not a string. So when using that in the function it caused the app to crash.
The right way to add the eventListener is like this:
Linking.addEventListener("url", event => handleInvite(event.url));
It is weird that no where in the docs this example is given. But it works now atleast!

How to make api calls when component is loaded multiple times

I need to fetch products each time a user navigates the products screen of a react native app being built with expo. I found out that the component lifecycle hook : componentDidMount is called just once. This is an issue because if the products are updated on the backend / API, if the componentDidMount is not called again when the user visits the product page again, they won't see latest products which defeats the purpose of the app. How may i approach this ?
Thanks
Use componentDidUpdate() method. This will execute automatically before render() method gets triggered.
Please read this to know about the life cycle of react-native.
Call a function inside componentDidUpdate() like this
componentDidMount()
{
this.loadInitialState();
}
and then do your API call and set state in loadInitialState() function. Hope this will work
Hope it helps .feel free for doubts.
You can add a navigation listener: Subscribe to updates to navigation lifecycle
this.props.navigation.addListener(
'didFocus',
() => {
this.getData()
}
)
use WebSocket for realtime application

Running api fetch on entering screen

I am creating an app in React Native (create react native) and I am attempting to fetch data from an API every time a user transitions to a screen.
For navigation, I am using the React Navigation library with a combination of Drawer and Stack Navigators.
Typically, I have seen fetch handled via the ComponentDidMount() lifecycle. However, when navigating to a screen in a stack navigator, the ComponentDidMount() lifecycle doesn't appear to trigger and the fetch doesn't run.
Ex. user is on post index, then navigates to add post screen, submits and is redirected to view screen (for that post), then clicks back to return to index. Returning to index does not trigger ComponentDidMount() and fetch isn't run again, so results are not updated.
Additionally, sometimes I need to access navigation params to alter a fetch request when navigation between screens.
I originally was attempting to determine screen transition (when navigation params were passed) via componentWillReceiveProps() method, however, this seemed a bit unreliable.
I did more reading and it sounds like I should be subscribing to listeners (via react navigation). I am having a hard time finding recent examples.
Current process (example)
On the desired screen I would subscribe to listener(s) in the componentDidMount() method:
async componentDidMount() {
this.subs = [this.props.navigation.addListener('willFocus', payload => this.setup(payload))];
}
Based of an example, it sounds like its good practice to remove all subs when unmounting the screen, so I also add:
componentWillUnmount() {
this.subs.forEach((sub) => {
sub.remove();
});
}
then I add a setup() callback method that calls whatever fetch methods I require:
setup = (payload) => {
this.getExampleDataFromApi();
};
Additionally, sometimes I need to access Navigation params that will be used in API queries.
I am setting these params via methods in other screens like so:
goToProfile = (id) => {
this.props.navigation.navigate('Profile', {
exampleParam: 'some value',
});
};
It seems like I cannot access the navigation prop via the provided getParam() method when within callback method from a navigation listener.
For example, this returns undefined.
setup = (payload) => {
console.log(navigation.getParam('exampleParam', []));
};
Instead I am having to do
componentDidFocus = (payload) => {
console.log(payload.action.params.exampleParam);
};
Question
I wanted to ask if my approach for handling fetch when navigating seems appropriate, and if not, what is a better way to tackle handling API requests when navigating between screens?
Thanks, I really appreciate the help!

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

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.

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.