|
1 | | -import { useEffect, type PropsWithChildren } from 'react'; |
| 1 | +import { isJSON } from 'es-toolkit'; |
| 2 | +import { useCallback, useEffect, type PropsWithChildren } from 'react'; |
| 3 | + |
| 4 | +import type { NativeMessage } from '@/libs/types/native'; |
| 5 | +import useGetIsLogin from '@/common/apis/useGetIsLogin'; |
| 6 | +import { useFCMStore } from '@/common/store/FCMStore'; |
| 7 | +import { usePatchFCMToken } from '@/common/apis/usePatchFCMToken'; |
2 | 8 |
|
3 | 9 | const NotificationProvider = ({ children }: PropsWithChildren) => { |
4 | | - useEffect(() => { |
5 | | - const handleMessage = (event: MessageEvent) => { |
6 | | - try { |
7 | | - const data = JSON.parse(event.data); |
8 | | - alert(data.message); |
9 | | - } catch (e) { |
10 | | - console.log(e); |
| 10 | + const { data: isLogin, isSuccess } = useGetIsLogin(); |
| 11 | + const { mutate: patchFCMToken } = usePatchFCMToken(); |
| 12 | + |
| 13 | + const fcmToken = useFCMStore(state => state.fcmToken); |
| 14 | + const setFcmToken = useFCMStore(state => state.setFcmToken); |
| 15 | + |
| 16 | + const isAuth = !!isLogin && isSuccess; |
| 17 | + |
| 18 | + // rn에서 Webview로 보낸 값을 수신하는 함수 |
| 19 | + const FCMTokenListener = useCallback( |
| 20 | + (event: MessageEvent) => { |
| 21 | + if (!isJSON(event.data)) return; |
| 22 | + |
| 23 | + const data = JSON.parse(event.data) as NativeMessage<string>; |
| 24 | + |
| 25 | + if (data.type === 'FCM_TOKEN') { |
| 26 | + setFcmToken(data.payload); |
11 | 27 | } |
12 | | - }; |
| 28 | + }, |
| 29 | + [setFcmToken], |
| 30 | + ); |
13 | 31 |
|
14 | | - window.addEventListener('message', handleMessage); |
| 32 | + useEffect(() => { |
| 33 | + if (isAuth && fcmToken) { |
| 34 | + patchFCMToken(fcmToken); |
| 35 | + } |
| 36 | + }, [isAuth, fcmToken, patchFCMToken]); |
15 | 37 |
|
16 | | - return () => window.removeEventListener('message', handleMessage); |
17 | | - }, []); |
| 38 | + useEffect(() => { |
| 39 | + // android, ios 구분하는 코드 |
| 40 | + document.addEventListener('message', FCMTokenListener as EventListener); |
| 41 | + window.addEventListener('message', FCMTokenListener as EventListener); |
18 | 42 |
|
| 43 | + return () => { |
| 44 | + document.removeEventListener('message', FCMTokenListener as EventListener); |
| 45 | + window.removeEventListener('message', FCMTokenListener as EventListener); |
| 46 | + }; |
| 47 | + }, [FCMTokenListener]); |
19 | 48 | return <>{children}</>; |
20 | 49 | }; |
21 | 50 | export default NotificationProvider; |
0 commit comments