Skip to content

Instantly share code, notes, and snippets.

@ChronSyn
Created April 17, 2020 19:52
Show Gist options
  • Save ChronSyn/232d4f18368cc1d646fbe002512d1d7e to your computer and use it in GitHub Desktop.
Save ChronSyn/232d4f18368cc1d646fbe002512d1d7e to your computer and use it in GitHub Desktop.
expo useNotification
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;
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