Search code examples
apolloreact-apolloapollo-client

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?


Solution

  • 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
        }
      },  
    )