Skip to content

Instantly share code, notes, and snippets.

@cruzach
Created October 1, 2020 21:06
Show Gist options
  • Save cruzach/d6d49089ffca1491d26fff1eed068494 to your computer and use it in GitHub Desktop.
Save cruzach/d6d49089ffca1491d26fff1eed068494 to your computer and use it in GitHub Desktop.
import * as Notifications from "expo-notifications";
import React, { useState, useEffect, useRef } from "react";
import { Text, View, Button, Platform } from "react-native";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
export default function App() {
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
useEffect(() => {
notificationListener.current = Notifications.addNotificationReceivedListener(
(notification) => {
alert("notif");
}
);
responseListener.current = Notifications.addNotificationResponseReceivedListener(
(response) => {
alert("response");
}
);
return () => {
Notifications.removeNotificationSubscription(notificationListener);
Notifications.removeNotificationSubscription(responseListener);
};
}, []);
return (
<View
style={{
flex: 1,
alignItems: "center",
justifyContent: "space-around",
}}
>
<View style={{ alignItems: "center", justifyContent: "center" }}>
<Text>
Title: {notification && notification.request.content.title}{" "}
</Text>
<Text>Body: {notification && notification.request.content.body}</Text>
<Text>
Data:{" "}
{notification && JSON.stringify(notification.request.content.data)}
</Text>
</View>
<Button
title="Press to schedule a notification"
onPress={async () => {
await schedulePushNotification();
}}
/>
</View>
);
}
async function schedulePushNotification() {
await Notifications.scheduleNotificationAsync({
content: {
title: "You've got mail! 📬",
body: "Here is the notification body",
data: { data: "goes here" },
},
trigger: { seconds: 2 },
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment