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:
Property | Type | Description |
---|---|---|
data | Ref<any/null> | The GraphQL subscription result’s data |
error | Ref<CombinedError> | Any errors encountered during subscription execution |
paused | ComputedRef<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:
Property | Type | Required | Description |
---|---|---|---|
query | string or DocumentNode or Ref<string> | Yes | The subscription to be executed |
variables | object or Ref<object> | No | The subscription variables |
paused | boolean , Ref<boolean> or ({ variables }) => boolean | No | If 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.