Created
April 17, 2020 19:52
-
-
Save ChronSyn/232d4f18368cc1d646fbe002512d1d7e to your computer and use it in GitHub Desktop.
expo useNotification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
import { TouchableOpacity, Text } from "react-native"; | |
import { Notifications } from "expo" | |
import { useNotification } from "./useNotification"; | |
const sendNotification = async () => await Notifications.presentLocalNotificationAsync( | |
{ | |
title: "Notified!", | |
body: "Hello, World!", | |
data: {} | |
} | |
); | |
const DemoComponent: React.FC<{}> = () => { | |
const [notification] = useNotification(); | |
return ( | |
<> | |
<Text> | |
Notification Source: { notification?.origin ?? "No Notification" } | |
</Text> | |
<TouchableOpacity onPress={async () => await sendNotification()}> | |
<Text>SEND NOTIFICATION</Text> | |
</TouchableOpacity> | |
</> | |
); | |
}; | |
export default DemoComponent; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
import { Notifications } from "expo"; | |
import { Notification } from "expo/build/Notifications/Notifications.types"; | |
type TSetNotification = [ | |
Notification, | |
(notification: Notification) => void | |
] | |
export const useNotification = (): TSetNotification => { | |
const [notification, setNotification]: TSetNotification = useState(null); | |
function onNotification(notification: Notification): void { | |
setNotification(notification) | |
} | |
function addListener(): void { | |
Notifications.addListener((notification: Notification) => onNotification(notification)) | |
} | |
useEffect(() => addListener(), []); | |
return [notification, setNotification]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment