Skip to content

Instantly share code, notes, and snippets.

@thehungrycoder
Created January 28, 2020 19:23
import { Notifications } from 'expo';
import { AppState, Platform } from 'react-native';
import { Component } from 'react';
const isIos = Platform.OS === 'ios';
export class NotificationHandler extends Component {
state = {
appState: AppState.current
};
handleNotification = async (notification = {}) => {
console.log('incoming push messsage', notification);
const { origin, data = {} } = notification;
const isAppActive = this.state.appState === 'active';
//ios does not show push notification when app in foreground
if (isIos && isAppActive) {
return //do something appropriate as the app is in foreground
}
if (origin === 'selected') {
//user pressed the notification, do something based on that.
}
};
handleAppState = nextAppState => {
this.setState({ appState: nextAppState });
};
async componentWillUnmount () {
(await this._notificationSubscription) &&
this._notificationSubscription.remove();
AppState.removeEventListener('change', this.handleAppState);
}
async componentDidMount () {
this._notificationSubscription = await Notifications.addListener(
this.handleNotification
);
AppState.addEventListener('change', this.handleAppState);
}
render () {
return null;
}
}
export default NotificationHandler;
@jozef5198
Copy link

Thanks man!

@tigpalmas
Copy link

Hi, im facing the same problem of handle notification when app is closed but was not abble to use this code. Could you provide me e full example how did you use this class ? Thank you so much.

@Ajju2211
Copy link

Ajju2211 commented Jul 4, 2021

yeah, same I'm not able to run this code.Could you please provide example project link.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment