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
Related
I want to clear errorMessage, when we navigate from Sign in to Sign up and vice-versa, for that I tried using onWillFocus but it has been deprecated.
Can anyone suggest me the replacement of onWillFocus?
You can use the original useEffect hook prescribed which gets triggered when a screen is loaded and when a state changes. You can either pass [] parameters so it only runs once or you can use a state to check it.
useEffect(() => {
// do you work here
}, []);
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
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!
I am working on a react-native app where I want to auto Reload a page can anyone tell me how can we do that in react-native code,
I have three component in which one component has to drop down I just want to reload the current screen this is the image of my page in which when a person changes the language i want to reload the page
use setTimeout on componentDidMount() to reload page.
example:
setTimeout(() => {
this.setState({time: true})
}, 1000)
You can use forceupdate see https://reactjs.org/docs/react-component.html#forceupdate
forceupdate will re-render the component.
https://facebook.github.io/react-native/docs/refreshcontrol.html
this is the guide for react native Refresh Component, usually we create function _onRefresh(), and you can callit at some specific time intervel.
Hope this answer will help you.
I'm assuming you are talking about auto-refreshing altered components in the simulator.
You would want to Enable Hot Reloading in the iOS or Android simulator.
You can pull up the developer screen in the iOS simulator showing Hot Reloading by pressing CMD + D.
Simple precise and clear!
componentWillMount(){
this._subscribe = this.props.navigation.addListener('didFocus', () => {
this.LoadData();
//Put your Data loading function here instead of my this.LoadData()
});}
This is more of a conceptional question, but I am not sure the exact way to solve it.
I have a component I want to download images from, but I want to be able to indicate that the component is loaded before the user can then use router flux to switch to it.
I am guessing that is something I would have to accomplish in redux, is that the right idea? I've been trying to find an example of a react native app that does this.
Thanks so much!
RN Image component a specific static method to handle this case: https://facebook.github.io/react-native/docs/image.html#prefetch
Note: Image.prefetch returns a Promise
Below is an example of how to implement this using React Native Router Flux (RNRF), without using Redux:
let urlOfImages = [https://...]
let preFetchTasks = [];
urlOfImages.forEach((p)=>{
preFetchTasks.push(Image.prefetch(p));
});
Promise.all(preFetchTasks).then((results)=>{
let downloadedAll = true;
results.forEach((result)=>{
if(!result){
//error occurred downloading a pic
downloadedAll = false;
}
})
if(downloadedAll){
Actions.someScene({ downloadedPics: urlOfImages})
}
})
Then in your someScene component use the image component like you normally do and the image will be fetched from your local disk cache rather then remotely :
<Image style={...} source={{uri: this.props.urlOfImages[0]}} />
Also just be aware you'll have issues if you attempt to load images from http rather than secured https endpoints: https://github.com/facebook/react-native/issues/8520
If you wanted to use it with Redux put the above code in an Action and make sure your reducers respond to the action and set the new state as per your application requirements.