Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApolloGraphQL: useSubscription Hook Syntax with onSubscriptionData?

I'm trying to build an Apollo useSubscription hook that uses onSubscriptionData.

I've looked in the Apollo docs, but I haven't yet an example.

E.g. something like:

const { loading, error, data } = useSubscription(
    INCOMING_MESSAGES_SUBSCRIPTION_QUERY,
    {
        variables: {"localUserId": Meteor.userId()},
        onSubscriptionData: myFunctionThatRunsWhenSubscriptionDataArrives
    }
);

That can't be right yet, because it doesn't include OnSubscriptionDataOptions<TData>, which is mentioned in the Apollo docs.

What is the correct way to build a useSubscription hook that uses onSubscriptionData?

like image 478
VikR Avatar asked Jan 18 '26 21:01

VikR


1 Answers

The onSubscriptionData function is passed a single options parameter of the type OnSubscriptionDataOptions. The options object has two properties:

  • client -- the ApolloClient instance used to query the server
  • subscriptionData -- an object with the following properties: loading, data, error

Example usage:

const { loading, error, data } = useSubscription(
  INCOMING_MESSAGES_SUBSCRIPTION_QUERY,
  {
    variables: {"localUserId": Meteor.userId()},
    onSubscriptionData: ({ subscriptionData: { data } }) => {
      // do something with `data` here
    }
  },  
)
like image 63
Daniel Rearden Avatar answered Jan 20 '26 20:01

Daniel Rearden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!