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:
- An application connected to the API
- Data already created to modify
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 '@/backend/data/resource'4
5type Todo = Schema["Todo"]6
7const client = generateClient<Schema>();8
9function MyComponent() {10 const [todos, setTodos] = useState<Todo[]>([])11
12 useEffect(() => {13 const sub = client.models.Todo.observeQuery()14 .subscribe({15 next: ({ items, isSynced }) => {16 setTodos(items)17 }18 })19 return () => sub.unsubscribe()20 }, [])21
22 return <ul>23 {todos.map(todo => <li key={todo.id}>{todo.content}</li>)}24 </ul>25}
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 '@/backend/data/resource';3
4const client = generateClient<Schema>();5
6// Subscribe to creation of Todo7const 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 Todo13const 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 Todo19const 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 subscription25createSub.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 '@/backend/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.
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.
TroubleshootingTroubleshoot 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'3
4const client = generateClient()5
6const fetchRecentData = () => {7 const { data: allTodos } = await client.models.Todo.list();8}9
10let priorConnectionState: ConnectionState;11
12Hub.listen("api", (data: any) => {13 const { payload } = data;14 if (15 payload.event === CONNECTION_STATE_CHANGE16 ) {17
18 if (priorConnectionState === ConnectionState.Connecting && payload.data.connectionState === ConnectionState.Connected) {19 fetchRecentData();20 }21 priorConnectionState = payload.data.connectionState;22 }23});24
25const createSub = client.models.Todo.onCreate().subscribe({26 next: payload => // Process incoming messages27});28
29const updateSub = client.models.Todo.onUpdate().subscribe({30 next: payload => // Process incoming messages31});32
33const deleteSub = client.models.Todo.onDelete().subscribe({34 next: payload => // Process incoming messages35});36
37const cleanupSubscriptions = () => {38 createSub.unsubscribe();39 updateSub.unsubscribe();40 deleteSub.unsubscribe();41}
Unsubscribe from a subscription
You can also unsubscribe from events by using subscriptions by implementing the following:
1// Stop receiving data updates from the subscription2sub.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: