Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated May 8, 2024

Subscribe to real-time events

In this guide, we will outline the benefits of enabling real-time data integrations and how to set up and filter these subscriptions. We will also cover how to unsubscribe from subscriptions.

Before you begin, you will need:

Set up a real-time list query

The recommended way to fetch a list of data is to use observeQuery to get a real-time list of your app data at all times. You can integrate observeQuery with React's useState and useEffect hooks in the following way:

1import { useState, useEffect } from 'react';
2import { generateClient } from 'aws-amplify/data';
3import type { Schema } from '../amplify/data/resource';
4
5type Todo = Schema['Todo']['type'];
6
7const client = generateClient<Schema>();
8
9export default function MyComponent() {
10 const [todos, setTodos] = useState<Todo[]>([]);
11
12 useEffect(() => {
13 const sub = client.models.Todo.observeQuery().subscribe({
14 next: ({ items, isSynced }) => {
15 setTodos([...items]);
16 },
17 });
18 return () => sub.unsubscribe();
19 }, []);
20
21 return (
22 <ul>
23 {todos.map((todo) => (
24 <li key={todo.id}>{todo.content}</li>
25 ))}
26 </ul>
27 );
28}

observeQuery fetches and paginates through all of your available data in the cloud. While data is syncing from the cloud, snapshots will contain all of the items synced so far and an isSynced status of false. When the sync process is complete, a snapshot will be emitted with all the records in the local store and an isSynced status of true.

Set up a real-time event subscription

Subscriptions is a feature that allows the server to send data to its clients when a specific event happens. For example, you can subscribe to an event when a new record is created, updated, or deleted through the API. Subscriptions are automatically available for any a.model() in your Amplify Data schema.

1import { generateClient } from 'aws-amplify/data';
2import type { Schema } from '../amplify/data/resource';
3
4const client = generateClient<Schema>();
5
6// Subscribe to creation of Todo
7const createSub = client.models.Todo.onCreate().subscribe({
8 next: (data) => console.log(data),
9 error: (error) => console.warn(error),
10});
11
12// Subscribe to update of Todo
13const updateSub = client.models.Todo.onUpdate().subscribe({
14 next: (data) => console.log(data),
15 error: (error) => console.warn(error),
16});
17
18// Subscribe to deletion of Todo
19const deleteSub = client.models.Todo.onDelete().subscribe({
20 next: (data) => console.log(data),
21 error: (error) => console.warn(error),
22});
23
24// Stop receiving data updates from the subscription
25createSub.unsubscribe();
26updateSub.unsubscribe();
27deleteSub.unsubscribe();

Set up server-side subscription filters

Subscriptions take an optional filter argument to define service-side subscription filters:

1import { generateClient } from 'aws-amplify/data';
2import type { Schema } from '../amplify/data/resource';
3
4const client = generateClient<Schema>();
5
6const sub = client.models.Todo.onCreate({
7 filter: {
8 content: {
9 contains: 'groceries',
10 },
11 },
12}).subscribe({
13 next: (data) => console.log(data),
14 error: (error) => console.warn(error),
15});

If you want to get all subscription events, don't specify any filter parameters.

Limitations:

  • Specifying an empty object {} as a filter is not recommended. Using {} as a filter might cause inconsistent behavior based on your data model's authorization rules.
  • If you're using dynamic group authorization and you authorize based on a single group per record, subscriptions are only supported if the user is part of five or fewer user groups.
  • Additionally, if you authorize by using an array of groups (groups: [String]),
    • subscriptions are only supported if the user is part of 20 or fewer groups
    • you can only authorize 20 or fewer user groups per record

Subscription connection status updates

Now that your application is set up and using subscriptions, you may want to know when the subscription is finally established, or reflect to your users when the subscription isn't healthy. You can monitor the connection state for changes through the Hub local eventing system.

1import { CONNECTION_STATE_CHANGE, ConnectionState } from 'aws-amplify/data';
2import { Hub } from 'aws-amplify/utils';
3
4Hub.listen('api', (data: any) => {
5 const { payload } = data;
6 if (payload.event === CONNECTION_STATE_CHANGE) {
7 const connectionState = payload.data.connectionState as ConnectionState;
8 console.log(connectionState);
9 }
10});

Subscription connection states

  • Connected - Connected and working with no issues.
  • ConnectedPendingDisconnect - The connection has no active subscriptions and is disconnecting.
  • ConnectedPendingKeepAlive - The connection is open, but has missed expected keep-alive messages.
  • ConnectedPendingNetwork - The connection is open, but the network connection has been disrupted. When the network recovers, the connection will continue serving traffic.
  • Connecting - Attempting to connect.
  • ConnectionDisrupted - The connection is disrupted and the network is available.
  • ConnectionDisruptedPendingNetwork - The connection is disrupted and the network connection is unavailable.
  • Disconnected - Connection has no active subscriptions and is disconnecting.
Troubleshooting
Troubleshoot connection issues and automated reconnection

Connections between your application and backend subscriptions can be interrupted for various reasons, including network outages or the device entering sleep mode. Your subscriptions will automatically reconnect when it becomes possible to do so.

While offline, your application will miss messages and will not automatically catch up when reconnected. Depending on your use case, you may want to take action for your app to catch up when it comes back online.

1import { generateClient, CONNECTION_STATE_CHANGE, ConnectionState } from 'aws-amplify/data'
2import { Hub } from 'aws-amplify/utils'
3import { Schema } from '../amplify/data/resource';
4
5const client = generateClient<Schema>()
6
7const fetchRecentData = () => {
8 const { data: allTodos } = await client.models.Todo.list();
9}
10
11let priorConnectionState: ConnectionState;
12
13Hub.listen("api", (data: any) => {
14 const { payload } = data;
15 if (
16 payload.event === CONNECTION_STATE_CHANGE
17 ) {
18
19 if (priorConnectionState === ConnectionState.Connecting && payload.data.connectionState === ConnectionState.Connected) {
20 fetchRecentData();
21 }
22 priorConnectionState = payload.data.connectionState;
23 }
24});
25
26const createSub = client.models.Todo.onCreate().subscribe({
27 next: payload => // Process incoming messages
28});
29
30const updateSub = client.models.Todo.onUpdate().subscribe({
31 next: payload => // Process incoming messages
32});
33
34const deleteSub = client.models.Todo.onDelete().subscribe({
35 next: payload => // Process incoming messages
36});
37
38const cleanupSubscriptions = () => {
39 createSub.unsubscribe();
40 updateSub.unsubscribe();
41 deleteSub.unsubscribe();
42}

Unsubscribe from a subscription

You can also unsubscribe from events by using subscriptions by implementing the following:

1// Stop receiving data updates from the subscription
2sub.unsubscribe();

Conclusion

Congratulations! You have finished the Subscribe to real-time events guide. In this guide, you set up subscriptions for real-time events and learned how to filter and cancel these subscriptions when needed.

Next steps

Our recommended next steps include continuing to build out and customize your information architecture for your data. Some resources that will help with this work include: