Amplify AppSync Subscription Uncaught (in promise)

Viewed 849

I am trying to use AWS amplify GraphQL subscription like below,

import Amplify,{ API, Storage, graphqlOperation } from "aws-amplify";
import awsmobile from "../../aws-exports";
Amplify.configure(awsmobile);
...
     const notiSubscription = API.graphql(graphqlOperation(onCreateNotification)).subscribe({
      next: (todoData) => {
        console.log(todoData);
      },
    });
...

onCreateNotification Graphql is,

 subscription OnCreateNotification {
onCreateNotification {
  id
}}

Below is the error I get,

AWSAppSyncProvider.ts:204 Uncaught (in promise) undefined

rejected    @   AWSAppSyncProvider.ts:204
Promise.then (async)        
step    @   AWSAppSyncProvider.ts:204
(anonymous) @   AWSAppSyncProvider.ts:204
push../node_modules/@aws-amplify/pubsub/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.__awaiter   @   AWSAppSyncProvider.ts:204
AWSAppSyncRealTimeProvider._startSubscriptionWithAWSAppSyncRealTime @   AWSAppSyncRealTimeProvider.ts:227
(anonymous) @   AWSAppSyncRealTimeProvider.ts:185
Subscription    @   Observable.js:197
subscribe   @   Observable.js:279
(anonymous) @   PubSub.ts:171
...

Please help me out in this, also my config is

"aws_project_region": "us-east-1",
    "aws_appsync_graphqlEndpoint": "https://xxx.appsync-api.us-east-1.amazonaws.com/graphql",
    "aws_appsync_region": "us-east-1",
    "aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
    "aws_appsync_apiKey": "xxxx",
1 Answers

You need to intialize the subscription in a useEffect() hook and then unsubscribe from the subscription.

 useEffect(() => {
    const subscription = API.graphql(graphqlOperation(onCreateNotification))
      .subscribe({
        next: todoData => {
        console.log(todoData);
        }
      })
      return () => subscription.unsubscribe()
  }, [])
Related