Apollo Elements Apollo Elements Guides API Blog Toggle darkmode

Haunted: useSubscription

Apollo useSubscription hook for web components.

Read the subscription components guides for examples and tips.

import { useSubscription, useState, component, html } from '@apollo-elements/hybrids';

import { UserAddedSubscription } from './UserAdded.subscription.graphql.js';

import '@material/mwc-snackbar';

function UserAdded() {
  const [last, setLast] = useState('');

  const [opened, setOpened] = useState(false);

  const { data } = useSubscription(UserAddedSubscription, {
    onData({ subscriptionData }) {
      setLast(subscriptionData.data.userAdded.name);
    }
  });

  return html`
    <link rel="stylesheet" href="user-added.css">
    <mwc-snackbar
        labeltext="${data?.name} Joined!"
        open="${opened}"
        @MDCSnackbar:closed="${() => setOpened(false)}"
        @MDCSnackbar:opened="${() => setOpened(true)}"
    ></mwc-snackbar>
  `,
};

customElements.define('user-added', component(UserAdded));

useSubscription

Parameters

query

ComponentDocument<D>

options

ApolloSubscriptionControllerOptions<D, V>
Option Type Description
client ApolloClient ApolloClient instance for the subscription.
fetchPolicy FetchPolicy See fetchPolicy
noAutoSubscribe boolean If set, the component will not subscribe until called explicitly. See noAutoSubscribe
onError (error: ApolloError) => void Callback for when subscription produces an error
onData (result: OnSubscriptionDataParams<Data<D>>) => void Callback for when subscription produces new data
onSubscriptionComplete () => void Callback for when the subscription ends
shouldResubscribe boolean Determines if your subscription should be unsubscribed and subscribed again
shouldSubscribe (op?: Partial<Operation<D, V>>) => boolean Predicate which determines whether to automatically subscribe. See shouldSubscribe
skip boolean When true, the subscription will not fetch at all.
subscription DocumentNode Subscription GraphQL Document
variables Variables<D, V> Subscription variables

Inherits from ApolloControllerOptions

Returns

ApolloSubscriptionController<D, V>

Exports

import { useSubscription } from '@apollo-elements/haunted/useSubscription';