@@ -42,7 +42,7 @@ Before you begin, you will need:
42
42
43
43
``` tsx title="src/App.tsx"
44
44
import type { EventsChannel } from ' aws-amplify/data' ;
45
- import { useState , useEffect } from ' react' ;
45
+ import { useState , useEffect , useRef } from ' react' ;
46
46
import { Amplify } from ' aws-amplify' ;
47
47
import { events } from ' aws-amplify/data' ;
48
48
@@ -53,32 +53,40 @@ Amplify.configure({
53
53
' https://abcdefghijklmnopqrstuvwxyz.appsync-api.us-east-1.amazonaws.com/event' ,
54
54
region: ' us-east-1' ,
55
55
defaultAuthMode: ' apiKey' ,
56
- apiKey: ' da2-abcdefghijklmnopqrstuvwxyz'
57
- }
58
- }
56
+ apiKey: ' da2-abcdefghijklmnopqrstuvwxyz' ,
57
+ },
58
+ },
59
59
});
60
60
61
61
export default function App() {
62
- const [myEvents, setMyEvents] = useState <unknown []>([]);
62
+ const [myEvents, setMyEvents] = useState <unknown []>([]);
63
+
64
+ const sub = useRef <ReturnType <EventsChannel [' subscribe' ]>>(null );
63
65
64
66
useEffect (() => {
65
67
let channel: EventsChannel ;
66
68
67
69
const connectAndSubscribe = async () => {
68
70
channel = await events .connect (' default/channel' );
69
71
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
+ }
77
81
};
78
82
79
83
connectAndSubscribe ();
80
84
81
- return () => channel && channel .close ();
85
+ return () => {
86
+ sub .current ?.unsubscribe ();
87
+ sub .current = null ;
88
+ return channel ?.close ();
89
+ };
82
90
}, []);
83
91
84
92
async function publishEvent() {
@@ -94,8 +102,8 @@ export default function App() {
94
102
<>
95
103
<button onClick = { publishEvent } >Publish Event</button >
96
104
<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 >
99
107
))}
100
108
</ul >
101
109
</>
0 commit comments