Skip to content

Instantly share code, notes, and snippets.

@arnaudambro
Last active December 13, 2020 21:35
Show Gist options
  • Save arnaudambro/7fecab1e94b1a9036b1977d36674f19e to your computer and use it in GitHub Desktop.
Save arnaudambro/7fecab1e94b1a9036b1977d36674f19e to your computer and use it in GitHub Desktop.
Listen to notifications
import React from 'react';
import { SafeAreaView, StyleSheet, View, Text, StatusBar, TouchableOpacity, Platform, Alert } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import Notifications from './NotificationService'
class App extends React.Component {
constructor(props) {
super(props);
Notifications.init(this.handleRegister);
}
handleRegister = async deviceToken => {
this.userId = DeviceInfo.getUniqueId();
this.registered = await fetch(`http://192.168.178.12:7777/save-token/${this.userId}/${deviceToken}`, {
method: 'POST',
}).then(res => res.ok);
};
componentDidMount() {
Notifications.listen(this.handleNotification);
}
handleNotification = (notification) => {
let customData = notification?.data?.customData;
if (!customData) return;
if (Platform.OS === 'android') customData = JSON.parse(customData);
// do what you need to do !
Alert.alert(Object.keys(customData)[0], customData[Object.keys(customData)[0]]);
};
componentWillUnmount() {
Notifications.delete();
}
handleNotificationPressWithDelay = delay => async () => {
const params = [this.userId, delay];
await fetch(`http://{YOUR_IP}:7777/test-send/${params.filter(p => p).join('/')}`)
.then(res => console.log({res}))
.catch(error => console.log({error}));
};
render() {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView style={styles.body}>
<TouchableOpacity
accessibilityRole={'button'}
onPress={this.handleNotificationPressWithDelay(10000)}
style={styles.linkContainer}>
<Text style={styles.link}>Notification in 10 seconds</Text>
</TouchableOpacity>
<View style={styles.separator} />
<TouchableOpacity
accessibilityRole={'button'}
onPress={this.handleNotificationPressWithDelay(0)}
style={styles.linkContainer}>
<Text style={styles.link}>Notification now</Text>
</TouchableOpacity>
</SafeAreaView>
</>
);
}
}
// styles in https://github.com/arnaudambro/push-notifications-test/blob/master/front/App.js
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment