From e48d7264dec72c5daad3365e2127519fee0c8cd1 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Mon, 13 Jun 2022 16:58:11 -0700 Subject: Handle push notification tokens --- modern/src/common/components/NativeInterface.js | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 modern/src/common/components/NativeInterface.js (limited to 'modern/src/common/components') diff --git a/modern/src/common/components/NativeInterface.js b/modern/src/common/components/NativeInterface.js new file mode 100644 index 00000000..75b954a8 --- /dev/null +++ b/modern/src/common/components/NativeInterface.js @@ -0,0 +1,64 @@ +import { useEffect, useState } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { useEffectAsync } from '../../reactHelper'; +import { sessionActions } from '../../store'; + +export const nativePostMessage = (message) => { + if (window.webkit && window.webkit.messageHandlers.appInterface) { + window.webkit.messageHandlers.appInterface.postMessage(message); + } + if (window.appInterface) { + window.appInterface.postMessage(message); + } +}; + +const listeners = new Set(); +window.updateNotificationToken = (token) => { + listeners.forEach((listener) => listener(token)); +}; + +const NativeInterface = () => { + const dispatch = useDispatch(); + + const user = useSelector((state) => state.session.user); + const [token, setToken] = useState(null); + + useEffect(() => { + const listener = (token) => setToken(token); + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, [setToken]); + + useEffectAsync(async () => { + if (user && token) { + setToken(null); + + const tokens = user.attributes.notificationTokens?.split(',') || []; + const updatedUser = { + ...user, + attributes: { + ...user.attributes, + notificationTokens: [...tokens, token].join(','), + }, + }; + + const response = await fetch(`/api/users/${user.id}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(updatedUser), + }); + + if (response.ok) { + dispatch(sessionActions.updateUser(await response.json())); + } else { + throw Error(await response.text()); + } + } + }, [user, token, setToken]); + + return null; +}; + +export default NativeInterface; -- cgit v1.2.3