useSubscription()

The useSubscription function allows you to execute GraphQL subscriptions, it requires a Provider or useClient to be configured in the component tree with a subscription forwarder configured, so make sure to set that up before using useSubscription.

The useSubscription function returns the following properties and functions:

PropertyTypeDescription
dataRef<any/null>The GraphQL subscription result's data
errorRef<CombinedError>Any errors encountered during subscription execution
isPausedRef<boolean>True if the subscription is paused or inactive
pause() => voidDeactivates the subscription temporarily until resume is called
resume() => voidActivates the subscription

Usage

The useSubscription function is slightly more complex and accepts two arguments, the first being the operation object which contains the following properties:

PropertyTypeRequiredDescription
querystring or DocumentNode or Ref<string>YesThe subscription to be executed
variablesobject or Ref<object>NoThe subscription variables

The second argument is what is called a Reducer which allows you aggregate subscription results. For more information about that, check the subscription guide.

Here is a full example of the usage:

function messagesReducer(oldValue, response) {
  oldValue = oldValue || [];
  if (!response.data || response.errors) {
    return oldValue;
  }

  return [...oldValue, response.data.newMessages];
}

const NewMessages = `
  subscription NewMessages {
    newMessages {
      id
      from
      message
    }
  }
`;

const { data } = useSubscription(
  {
    query: NewMessages,
  },
  messagesReducer
);

Reactivity

Subscriptions are fired once and continuously keep emitting results. Because of that, useSubscription doesn't accept any reactive queries or variables you may pass.

For more information about subscriptions, you can check the subscription guide.