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
pausedComputedRef<boolean>True if the subscription is paused or inactive. This is readonly, and you should control it by the passed paused value.

Usage

The useSubscription function 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
pausedboolean, Ref<boolean> or ({ variables }) => booleanNoIf the subscription should be paused, if true any incoming values will be ignored by the reducer

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

Here is a full example of the usage:

vue<script setup>
import { useSubscription } from 'villus';

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
);
</script>

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.