Skip to content

fix(events): update events react example code #8330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 23, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Before you begin, you will need:

```tsx title="src/App.tsx"
import type { EventsChannel } from 'aws-amplify/data';
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { Amplify } from 'aws-amplify';
import { events } from 'aws-amplify/data';

Expand All @@ -53,32 +53,40 @@ Amplify.configure({
'https://abcdefghijklmnopqrstuvwxyz.appsync-api.us-east-1.amazonaws.com/event',
region: 'us-east-1',
defaultAuthMode: 'apiKey',
apiKey: 'da2-abcdefghijklmnopqrstuvwxyz'
}
}
apiKey: 'da2-abcdefghijklmnopqrstuvwxyz',
},
},
});

export default function App() {
const [myEvents, setMyEvents] = useState<unknown[]>([]);
const [myEvents, setMyEvents] = useState<unknown[]>([]);

const sub = useRef<ReturnType<EventsChannel['subscribe']>>(null);

useEffect(() => {
let channel: EventsChannel;

const connectAndSubscribe = async () => {
channel = await events.connect('default/channel');

channel.subscribe({
next: (data) => {
console.log('received', data);
setMyEvents((prev) => [data, ...prev]);
},
error: (err) => console.error('error', err)
});
if (!sub.current) {
sub.current = channel.subscribe({
next: (data) => {
console.log('received', data);
setMyEvents((prev) => [data, ...prev]);
},
error: (err) => console.error('error', err),
});
}
};

connectAndSubscribe();

return () => channel && channel.close();
return () => {
sub.current?.unsubscribe();
sub.current = null;
return channel?.close();
};
}, []);

async function publishEvent() {
Expand All @@ -94,8 +102,8 @@ export default function App() {
<>
<button onClick={publishEvent}>Publish Event</button>
<ul>
{myEvents.map((data) => (
<li key={data.id}>{JSON.stringify(data.event)}</li>
{myEvents.map((data, idx) => (
<li key={idx}>{JSON.stringify(data.event, null, 2)}</li>
))}
</ul>
</>
Expand Down