useSubscription
⚠️ NOTE: This document still needs to be updated for Apollo React/Relay Duct-Tape.
useSubscription
Hook used to subscribe and unsubscribe to a subscription.
import {graphql, useSubscription} from 'react-relay';
import {useMemo} from 'react';
const subscription = graphql`
subscription UserDataSubscription($input: InputData!) {
# ...
}
`;
function UserComponent({ id }) {
// IMPORTANT: your config should be memoized.
// Otherwise, useSubscription will re-render too frequently.
const config = useMemo(() => ({
variables: {id},
subscription,
}), [id, subscription]);
useSubscription(config);
return (/* ... */);
}
Arguments
config
: a config of typeGraphQLSubscriptionConfig
passed torequestSubscription
requestSubscriptionFn
:?<TSubscriptionPayload>(IEnvironment, GraphQLSubscriptionConfig<TSubscriptionPayload>) => Disposable
. An optional function with the same signature asrequestSubscription
, which will be called in its stead. Defaults torequestSubscription
.
Type GraphQLSubscriptionConfig<TSubscriptionPayload>
- An object with the following fields:
cacheConfig
: [Optional]CacheConfig
subscription
:GraphQLTaggedNode
. A GraphQL subscription specified using agraphql
template literalvariables
: The variables to pass to the subscriptiononCompleted
: [Optional]() => void
. An optional callback that is executed when the subscription is establishedonError
: [Optional](Error) => {}
. An optional callback that is executed when an error occursonNext
: [Optional](TSubscriptionPayload) => {}
. An optional callback that is executed when new data is receivedupdater
: [Optional]SelectorStoreUpdater
.
Flow Type Parameters
TSubscriptionPayload
: The type of the payloads vended by the subscription. You should pass the flow type imported from the auto-generated.graphql
file corresponding to the subscription, e.g. useUserDataSubscription
as the type parameter, fromimport type {UserDataSubscription} from './__generated__/UserDataSubscription.graphql'
;
Behavior
- This is only a thin wrapper around the
requestSubscription
API. It will:- Subscribe when the component is mounted with the given config
- Unsubscribe when the component is unmounted
- Unsubscribe and resubscribe with new values if the environment, config or
requestSubscriptionFn
changes.
- If you have the need to do something more complicated, such as imperatively requesting a subscription, please use the
requestSubscription
API directly. - See the GraphQL Subscriptions Guide for a more detailed explanation of how to work with subscriptions.
note
useSubscription
doesn't automatically add client_subscription_id
. You may need to provide an arbitrary client_subscription_id
to config.variables.input