child_added on stackNavigator dont fire componentWillUnmount - react-native

StackNavigator does not trigger the componentWillUnmount event, so two listeners remain open.
Is there any way to capture the "OnTabChange" event to stop the listener?
If the user changes quickly from one tab to another, would this be the best option?
I have also thought about creating a listener in the App.js file so that it emits a message (with the snapshot) and capture this event by the screen that listener listens to.
I was think to made a listener in App.js like
firebase.authFirebaseListener = auth.onAuthStateChanged((user) => {
if (user) {
db.ref('users')
.child(auth.currentUser.uid)
.child('favorites')
.on('child_added', snapshotFavorites => {
## Send a signal with snapshotFavorites
## to refresh data if current screen need it.
})
....
}
}
componentWillUnmount() {
db.ref('users').child(auth.currentUser.uid).child('favorites').off()
db.ref('users').child(auth.currentUser.uid).off()
db.ref('users').off()
}

I'm not sure if it's the same thing, but I used react-navigation-is-focused-hoc and added a listener to the page I wanted to trigger ComponentWillMount and detect changes.
Give it a look, I used in the exact way the tutorial of it says in github.

Related

React Native - Global BackHandler behavior depends on registration timing

I'm migrating an old React Native app from 0.57 to 0.62, and just setup navigation with the current React Navigation package. That app contains a global navigation store that registers to Android back button presses and allows me to intercept back operations, no matter where they originate (hardware button or programmatically).
I have a rather weird behavior here, and it seems to be timing-related. In the snippet below, I register a listener with BackHandler, which supresses back button taps and logs a warning. I'll register it in the componentDidMount method.
export class RootComponent extends React.Component {
private initBackButton() {
const onBackPress = () => {
console.warn("BACK BUTTON SUPPRESSED");
return true;
};
BackHandler.addEventListener("hardwareBackPress", onBackPress);
}
public componentDidMount() {
// TODO register back listener
}
public render() {
return (
<NavigationContainer >
<StackNavigatorSetup />
</NavigationContainer>
);
}
}
If I register the listener synchronously, the back button listener fires if I press it at the initial screen of my StackNavigator.
If I navigate to a second screen, the listener does not fire if I press the back button, and I can return back to the start screen. If I press back there again, the listener fires.
Note that I'm declaring the listener in the root component, so that component isn't going anywhere.
public componentDidMount() {
// only works on the start screen
this.initBackButton();
}
Now, the behavior is different if I use a delay:
If I register the same handler with a delay of 1 second, the handler works on any screen
This is not thread-related. If I use a delay that is too short, it again only works on the start screen
public componentDidMount() {
// works on every screen i'll navigate to
PromiseUtil.delay(1000).then(() => this.initBackButton());
}
To be honest, I don't really have a clue what's happening here. BackHandler seems to be ready, but I don't understand why the listener works either global or not depending on the delay. Also, my root component doesn't really change, so I wonder whether React Navigation is messing with me here...

Vue: beforeunload event listener is not being removed

I'm working on an undo delete functionality, it consist of a small modal which allows the user to undo/delay the action for a limited amount of time(similar to gmail). However, I want to ensure that the action is executed if the user decides to navigate to another window or close the tab, which I am doing like so:
mounted() {
this.timeout = setTimeout(() => {
this.close(true);
}, this.duration);
window.addEventListener('beforeunload', this.forceDestroyHandler, { capture: true });
},
methods: {
close(deleteBeforeClosing) {
if (deleteBeforeClosing) {
clearTimeout(this.timeout);
// This is the function dispatching to the store and deleting the item
this.destructiveEvent(this.category, this.item.id);
}
this.$emit('close');
}
I am then (attempting) to remove the event listener on beforeDestroy:
beforeDestroy() {
this.forceDestroy();
window.removeEventListener('beforeunload', this.forceDestroyHandler, {capture: true});
},
However, it appears that beforeDestroy is never called, meaning the event listener is never removed - so if the user decides the close the tab or navigate, he is prompted a message even tough the undo component is not even showing anymore. If the user would click on cancel, another action would be dispatched to the store attempting to delete an already deleted item causing an server error.
I also tried to put the removeEventListener elsewhere but I am keep having the same issue.
To further elabourate on my comment: the reason why your onbeforeunload event listener is not unbound is because the beforeDestroy() lifecycle hook is only fired when a VueJS component is destroyed. When you close the browser tab/window, the entire thread is wiped and this does not trigger component destruction.
Since you only want to remove the listener after the modal is closed, it makes sense to do it in the close() method: hence why you approach worked.

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!

Expo.js: Capture event when my app goes into the background?

If I'm using my app and then switch out of it using the home button, app switcher, etc, Is there a way to reliably run some code when this event is detected? I want to do some tasks such as cancelling timers, scheduling notifications, and so on.
You can track app's state using AppState provided by 'react-native'
By using AppState.currentState you will know whether the app is in foreground, background, active or inactive. If you want to perform some tasks whenever the state changes you can use event listeners provided by AppState.
You can add the following logic in your Component to get it done -
componentDidMount() {
AppState.addEventListener('change', this.handleStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleStateChange);
}
handleStateChange will be called every time the app moves from foreground to background or vice-versa with the app's current state passed as an argument.
For further reference see the docs
Hope it helped.

Clear Previous Expo Push Notifications

I have my app in Expo pushing a notification when somebody sends a message, but if that person sends multiple messages a second notification is pushed.
Is there anything I can do to clear the previous notification, or simply update the notification instead of adding a second notification to the list?
Basically I need to force an override or dismiss previous notifications.
The approach I was hoping to use was to add a listener which cleared notifications before appending, but it seems that this only works when the app is in the foreground.
Is there a recommended approach to this currently?
You can clear any or all previous notifications in expo-notifications. Your question is not clear but I am guessing you want to clear all previous notification if new notification is received. You have to spot the best place when to clear notifications on your code. But here are some tips (use the following code in the useEffect hook) -
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
// DISMISS ALL NOTIFICATION AFTER INTERACTION
Notifications.dismissAllNotificationsAsync();
});
If you want to dismiss specific notification in that case, use dismissNotificationAsync(identifier: string): Promise method.
Just in case, if you want to dismiss all notifications when receiving a new one while the app is foregrounded (use the following code in the useEffect hook).
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
// setNotification(notification);
// DISMISS ALL NOTIFICATION UPON RECEIVING NOTIFICATION WHILE IN FOREGROUND
Notifications.dismissAllNotificationsAsync();
});
You can use Notifications.dismissAllNotificationsAsync() method or dismissNotificationAsync(identifier: string): Promise method anywhere you like but you need to spot where to best use them.
_handleNotification = (notification) => {
this.setState({notification: notification});
console.log('get notification', this.state.notification);
let localnotificationId = this.state.notification.notificationId;
setTimeout(function () {
Notifications.dismissNotificationAsync(localnotificationId);
}, 10000)
};
This is how I do in NodeJS