@@ -42,7 +42,7 @@ Before you begin, you will need:
4242
4343``` tsx title="src/App.tsx"
4444import type { EventsChannel } from ' aws-amplify/data' ;
45- import { useState , useEffect } from ' react' ;
45+ import { useState , useEffect , useRef } from ' react' ;
4646import { Amplify } from ' aws-amplify' ;
4747import { events } from ' aws-amplify/data' ;
4848
@@ -53,32 +53,40 @@ Amplify.configure({
5353 ' https://abcdefghijklmnopqrstuvwxyz.appsync-api.us-east-1.amazonaws.com/event' ,
5454 region: ' us-east-1' ,
5555 defaultAuthMode: ' apiKey' ,
56- apiKey: ' da2-abcdefghijklmnopqrstuvwxyz'
57- }
58- }
56+ apiKey: ' da2-abcdefghijklmnopqrstuvwxyz' ,
57+ },
58+ },
5959});
6060
6161export default function App() {
62- const [myEvents, setMyEvents] = useState <unknown []>([]);
62+ const [myEvents, setMyEvents] = useState <unknown []>([]);
63+
64+ const sub = useRef <ReturnType <EventsChannel [' subscribe' ]>>(null );
6365
6466 useEffect (() => {
6567 let channel: EventsChannel ;
6668
6769 const connectAndSubscribe = async () => {
6870 channel = await events .connect (' default/channel' );
6971
70- channel .subscribe ({
71- next : (data ) => {
72- console .log (' received' , data );
73- setMyEvents ((prev ) => [data , ... prev ]);
74- },
75- error : (err ) => console .error (' error' , err )
76- });
72+ if (! sub .current ) {
73+ sub .current = channel .subscribe ({
74+ next : (data ) => {
75+ console .log (' received' , data );
76+ setMyEvents ((prev ) => [data , ... prev ]);
77+ },
78+ error : (err ) => console .error (' error' , err ),
79+ });
80+ }
7781 };
7882
7983 connectAndSubscribe ();
8084
81- return () => channel && channel .close ();
85+ return () => {
86+ sub .current ?.unsubscribe ();
87+ sub .current = null ;
88+ return channel ?.close ();
89+ };
8290 }, []);
8391
8492 async function publishEvent() {
@@ -94,8 +102,8 @@ export default function App() {
94102 <>
95103 <button onClick = { publishEvent } >Publish Event</button >
96104 <ul >
97- { myEvents .map ((data ) => (
98- <li key = { data . id } >{ JSON .stringify (data .event )} </li >
105+ { myEvents .map ((data , idx ) => (
106+ <li key = { idx } >{ JSON .stringify (data .event , null , 2 )} </li >
99107 ))}
100108 </ul >
101109 </>
0 commit comments