|
| 1 | +import React, { useEffect, useState } from "react"; |
| 2 | +import { EventSourcePolyfill } from "event-source-polyfill"; |
| 3 | +import { |
| 4 | + addNotification, |
| 5 | + clearNotifications, |
| 6 | +} from "../../redux/modules/notificationSlice"; |
| 7 | +import { useDispatch, useSelector } from "react-redux"; |
| 8 | + |
| 9 | +const NotificationsTest = () => { |
| 10 | + const dispatch = useDispatch(); |
| 11 | + //notifications 를 가져와 notifications 변수에 할당 |
| 12 | + const notifications = useSelector( |
| 13 | + (state) => state.notification.notifications |
| 14 | + ); |
| 15 | + |
| 16 | + useEffect(() => { |
| 17 | + const accessToken = localStorage.getItem("accessToken"); |
| 18 | + // SSE 연결을 위해 EventSource 객체를 생성 |
| 19 | + const eventSource = new EventSourcePolyfill( |
| 20 | + `http://shinjeong.shop/pushs?token=${accessToken}` |
| 21 | + ); |
| 22 | + // const eventSource = new EventSourcePolyfill(`/pushs`); |
| 23 | + |
| 24 | + // SSE 연결 성공 시 호출되는 이벤트 핸들러 |
| 25 | + eventSource.onopen = () => { |
| 26 | + console.log("SSE 연결완료"); |
| 27 | + }; |
| 28 | + // SSE 메시지 수신 시 호출되는 이벤트 핸들러 함수를 등록하여 SSE 메시지가 도착했을 때의 동작을 정의 |
| 29 | + eventSource.onmessage = (event) => { |
| 30 | + const data = JSON.parse(event.data); |
| 31 | + console.log("알림이 도착했습니다", data); |
| 32 | + alert("알림이 도착했습니다", data); |
| 33 | + //addNotification액션 dispatch |
| 34 | + dispatch(addNotification(data)); |
| 35 | + }; |
| 36 | + |
| 37 | + // SSE 연결 오류 발생 시 호출되는 이벤트 핸들러 |
| 38 | + eventSource.onerror = (error) => { |
| 39 | + console.error("SSE 에러발생!", error); |
| 40 | + }; |
| 41 | + |
| 42 | + return () => { |
| 43 | + eventSource.close(); |
| 44 | + dispatch(clearNotifications()); |
| 45 | + }; |
| 46 | + }, [dispatch]); |
| 47 | + return ( |
| 48 | + <div> |
| 49 | + <h2> Notifications List </h2> |
| 50 | + {notifications.map((notification) => ( |
| 51 | + <div key={notification.id}> |
| 52 | + <span>{notification.message}</span> |
| 53 | + </div> |
| 54 | + ))} |
| 55 | + </div> |
| 56 | + ); |
| 57 | +}; |
| 58 | + |
| 59 | +export default NotificationsTest; |
0 commit comments