ApolloSubscription

Subscription components update in real time in reaction to events on your GraphQL server. They are ideal for uses like chat rooms or stock tickers.

Subscription components inherit the ApolloElementInterface.

Properties

updateComplete

(read-only)
Promise<boolean>

Methods

requestUpdate

Parameters

name

string

value

unknown

Returns

void

addController

Parameters

controller

ReactiveController

Returns

void

removeController

Parameters

controller

ReactiveController

Returns

void

Private Methods

update

protected

Parameters

args

any[]

Returns

void

updated

protected

Parameters

args

any[]

Returns

void
Common base interface for apollo elements

Properties

documentType

static(read-only)
'document'|'query'|'mutation'|'subscription'

client

public
ApolloClient | null
The Apollo Client instance.

controller

public
ApolloController<D, V>

document

public
ComponentDocument<D, V> | null
Operation document.GraphQL operation document i.e. query, subscription, or mutation. Must be a parsed GraphQL DocumentNode, so use graphql-tag.

data

public
Data<D> | null
Latest Data.

variables

public
Variables<D, V> | null
Operation variables.

error

public
Error | null
Latest error

errors

public
readonly GraphQLError[]
Latest errors

loading

public
boolean
Whether a request is in flight.

fetchPolicy

public
string | undefined
Fetch Policy for the operation.

context

public
Record<string, unknown> | undefined
Context passed to the link execution chain.

errorPolicy

public
ErrorPolicy | undefined
Error Policy for the operation.

Much like fetchPolicy, errorPolicy allows you to control how GraphQL errors from the server are sent to your UI code. By default, the error policy treats any GraphQL Errors as network errors and ends the request chain. It doesn’t save any data in the cache, and renders your UI with the error property set to an ApolloError. By changing this policy per request, you can adjust how GraphQL Errors are managed by your UI. The possible options for errorPolicy are:

  • none (default): any errors from the request are treated like runtime errors and the observable is stopped (XXX this is default to lower breaking changes going from AC 1.0 => 2.0)
  • ignore: errors from the request do not stop the observable, but also don’t call next
  • all: errors are treated like data and will notify observables

readyToReceiveDocument

public
boolean
True when the element is connected and ready to receive its GraphQL document

Events

apollo-element-connected

ApolloElementEvent
The element connected to the DOM

apollo-element-disconnected

ApolloElementEvent
The element disconnected from the DOM

Private Methods

documentChanged

protectedLifecycle callback that reacts to changes in the GraphQL document

Parameters

document

ComponentDocument<D, V> | null

Returns

void

variablesChanged

protectedLifecycle callback that reacts to changes in the operation variables

Parameters

variables

Variables<D, V> | null

Returns

void

Common interface for mutation elements

See ApolloElementInterface for more information on events

Properties

documentType

static(read-only)
'document'|'query'|'mutation'|'subscription'

controller

public
ApolloController<D, V>

data

public
Data<D> | null
Latest mutation data

variables

public
Variables<D, V> | null
Mutation variables.An object that maps from the name of a variable as used in the mutation GraphQL document to that variable’s value.

awaitRefetchQueries

public
boolean | undefined
Queries refetched as part of refetchQueries are handled asynchronously, and are not waited on before the mutation is completed (resolved). Setting this to true will make sure refetched queries are completed before the mutation is considered done. false by default.

called

public(read-only)
boolean
Whether the mutation was called.

fetchPolicy

public
string | undefined
Fetch Policy for the operation.If set to ’no-cache’, the mutation result will not update the Apollo cache.

ignoreResults

public
boolean
If true, the returned data property will not update with the mutation result.

mutation

public
ComponentDocument<D, V> | null
The mutation.

optimisticResponse

public
OptimisticResponseType<D, V> | undefined

An object that represents the result of this mutation that will be optimistically stored before the server has actually returned a result.

This is most often used for optimistic UI, where we want to be able to see the result of a mutation immediately, and update the UI later if any errors appear.

refetchQueries

public
RefetchQueriesType<D> | null
A list of query names which will be refetched once this mutation has returned. This is often used if you have a set of queries which may be affected by a mutation and will have to update. Rather than writing a mutation query reducer (i.e. updateQueries) for this, you can refetch the queries that will be affected and achieve a consistent store once these queries return.

client

public
ApolloClient | null
The Apollo Client instance.

document

public
ComponentDocument<D, V> | null
Operation document.GraphQL operation document i.e. query, subscription, or mutation. Must be a parsed GraphQL DocumentNode, so use graphql-tag.

error

public
Error | null
Latest error

errors

public
readonly GraphQLError[]
Latest errors

loading

public
boolean
Whether a request is in flight.

context

public
Record<string, unknown> | undefined
Context passed to the link execution chain.

errorPolicy

public
ErrorPolicy | undefined
Error Policy for the operation.

Much like fetchPolicy, errorPolicy allows you to control how GraphQL errors from the server are sent to your UI code. By default, the error policy treats any GraphQL Errors as network errors and ends the request chain. It doesn’t save any data in the cache, and renders your UI with the error property set to an ApolloError. By changing this policy per request, you can adjust how GraphQL Errors are managed by your UI. The possible options for errorPolicy are:

  • none (default): any errors from the request are treated like runtime errors and the observable is stopped (XXX this is default to lower breaking changes going from AC 1.0 => 2.0)
  • ignore: errors from the request do not stop the observable, but also don’t call next
  • all: errors are treated like data and will notify observables

readyToReceiveDocument

public
boolean
True when the element is connected and ready to receive its GraphQL document

Methods

onCompleted

publicCallback for when a mutation is completed.

Parameters

_data

Data<D>

Returns

void

onError

publicCallback for when an error occurs in mutation.

Parameters

_error

Error

Returns

void

updater

public

A function which updates the apollo cache when the query responds. This function will be called twice over the lifecycle of a mutation. Once at the very beginning if an optimisticResponse was provided. The writes created from the optimistic data will be rolled back before the second time this function is called which is when the mutation has succesfully resolved. At that point update will be called with the actual mutation result and those writes will not be rolled back.

The reason a DataProxy is provided instead of the user calling the methods directly on ApolloClient is that all of the writes are batched together at the end of the update, and it allows for writes generated by optimistic data to be rolled back.

Examples

Updating a query
updater(cache, result) {
  cache.writeQuery({
    query: MyProfileQuery,
    data: { profile: result.data.updateMyProfile },
  });
}

Parameters

params

any[]

Returns

any

mutate

publicThis resolves a single mutation according to the options specified and returns a Promise which is either resolved with the resulting data or rejected with an error.

Parameters

params

Partial<MutationOptions<Data<D>, Variables<D, V>>>

All named arguments to mutate default to the element’s corresponding instance property. So you can call element.mutate() without arguments and it will call using element.mutation, element.variables, etc. You can likewise override instance properties per-call by passing them in, e.g.

await element.mutate({
  fetchPolicy: 'network-only'
  variables: {
    ...element.variables,
    name: 'overridden',
  },
});
Property Type Description
awaitRefetchQueries boolean See awaitRefetchQueries
context Record<string, unknown> See context
errorPolicy ErrorPolicy See errorPolicy
fetchPolicy FetchPolicy See fetchPolicy
mutation DocumentNode See mutation
optimisticResponse OptimisticResponseType<D, V> See optimisticResponse
refetchQueries RefetchQueriesType<D, V> See refetchQueries
update MutationUpdaterFn<Data<D>, Variables<D, V>> See updater
variables Variables<D, V> See variables

Returns

Promise<FetchResult<Data<D>>>
Property Type Description
data Data<D, V> The result of a successful execution of the mutation
errors readonly GraphQLError[] included when any errors occurred as a non-empty array
extensions boolean Reserved for adding non-standard properties
context Record<string, unknown> See context

Events

apollo-mutation-result

CustomEvent<FetchResult<Data<D>>>
The mutation resolved

apollo-error

CustomEvent<ApolloError>
The mutation rejected

apollo-element-connected

ApolloElementEvent
The element connected to the DOM

apollo-element-disconnected

ApolloElementEvent
The element disconnected from the DOM

Private Methods

documentChanged

protectedLifecycle callback that reacts to changes in the GraphQL document

Parameters

document

ComponentDocument<D, V> | null

Returns

void

variablesChanged

protectedLifecycle callback that reacts to changes in the operation variables

Parameters

variables

Variables<D, V> | null

Returns

void

Common interface for query elements

See ApolloElementInterface for more information on events

Properties

documentType

static(read-only)
'document'|'query'|'mutation'|'subscription'

controller

public
ApolloController<D, V>

data

public
Data<D> | null
The latest query data.

variables

public
Variables<D, V> | null
Query variables.

An object map from variable name to variable value, where the variables are used within the GraphQL query.

Setting variables will initiate the query, unless noAutoSubscribe is also set.

fetchPolicy

public
string | undefined
The fetchPolicy for the query.

Determines where the client may return a result from. The options are:

  • cache-first (default): return result from cache, fetch from network if cached result is not available.
  • cache-and-network: return result from cache first (if it exists), then return network result once it’s available.
  • cache-only: return result from cache if available, fail otherwise.
  • no-cache: return result from network, fail if network call doesn’t succeed, don’t save to cache
  • network-only: return result from network, fail if network call doesn’t succeed, save to cache
  • standby: only for queries that aren’t actively watched, but should be available for refetch and updateQueries.

canAutoSubscribe

public(read-only)
boolean
Flags an element that’s ready and able to auto subscribe

options

public
ApolloQueryControllerOptions<D, V>
Option Type Description
fetchPolicy WatchQueryFetchPolicy The fetchPolicy for the query.
variables Variables<D, V> Variables for the query.
noAutoSubscribe boolean If true, the element will not begin querying data until you manually call subscribe
shouldSubscribe (op?: Partial<Operation<D, V>>) => boolean Determines whether the element should attempt to subscribe automatically\nOverride to prevent subscribing unless your conditions are met
onData (data: Data<D>) => void Optional callback for when a query resolves.
onError (error: Error) => void Optional callback for when an error occurs.

Inherits from ApolloControllerOptions

networkStatus

public
NetworkStatus

networkStatus is useful if you want to display a different loading indicator (or no indicator at all) depending on your network status as it provides a more detailed view into the state of a network request on your component than loading does. networkStatus is an enum with different number values between 1 and 8. These number values each represent a different network state.

  1. loading: The query has never been run before and the request is now pending. A query will still have this network status even if a result was returned from the cache, but a query was dispatched anyway.
  2. setVariables: If a query’s variables change and a network request was fired then the network status will be setVariables until the result of that query comes back. React users will see this when options.variables changes on their queries.
  3. fetchMore: Indicates that fetchMore was called on this query and that the network request created is currently in flight.
  4. refetch: It means that refetch was called on a query and the refetch request is currently in flight.
  5. Unused.
  6. poll: Indicates that a polling query is currently in flight. So for example if you are polling a query every 10 seconds then the network status will switch to poll every 10 seconds whenever a poll request has been sent but not resolved.
  7. ready: No request is in flight for this query, and no errors happened. Everything is OK.
  8. error: No request is in flight for this query, but one or more errors were detected.

If the network status is less then 7 then it is equivalent to loading being true. In fact you could replace all of your loading checks with networkStatus < 7 and you would not see a difference. It is recommended that you use loading, however.

nextFetchPolicy

public
WatchQueryFetchPolicy | NextFetchPolicyFunction<D, V> | undefined
Set to prevent subsequent network requests when the fetch policy is cache-and-network or network-only.When someone chooses cache-and-network or network-only as their initial FetchPolicy, they often do not want future cache updates to trigger unconditional network requests, which is what repeatedly applying the cache-and-network or network-only policies would seem to imply. Instead, when the cache reports an update after the initial network request, it may be desirable for subsequent network requests to be triggered only if the cache result is incomplete. The nextFetchPolicy option provides a way to update options.fetchPolicy after the intial network request, without having to set options.

noAutoSubscribe

public
boolean
When true, the component will not automatically subscribe to new data. Call the subscribe() method to do so.

partial

public(read-only)
boolean | undefined
True when the query returned partial data.If data was read from the cache with missing fields, partial will be true. Otherwise, partial will be falsy.

pollInterval

public
number | undefined
The time interval (in milliseconds) on which this query should be refetched from the server.

query

public
DocumentNode | ComponentDocument<D, V> | null
A GraphQL document containing a single query.

client

public
ApolloClient | null
The Apollo Client instance.

document

public
ComponentDocument<D, V> | null
Operation document.GraphQL operation document i.e. query, subscription, or mutation. Must be a parsed GraphQL DocumentNode, so use graphql-tag.

error

public
Error | null
Latest error

errors

public
readonly GraphQLError[]
Latest errors

loading

public
boolean
Whether a request is in flight.

context

public
Record<string, unknown> | undefined
Context passed to the link execution chain.

errorPolicy

public
ErrorPolicy | undefined
Error Policy for the operation.

Much like fetchPolicy, errorPolicy allows you to control how GraphQL errors from the server are sent to your UI code. By default, the error policy treats any GraphQL Errors as network errors and ends the request chain. It doesn’t save any data in the cache, and renders your UI with the error property set to an ApolloError. By changing this policy per request, you can adjust how GraphQL Errors are managed by your UI. The possible options for errorPolicy are:

  • none (default): any errors from the request are treated like runtime errors and the observable is stopped (XXX this is default to lower breaking changes going from AC 1.0 => 2.0)
  • ignore: errors from the request do not stop the observable, but also don’t call next
  • all: errors are treated like data and will notify observables

readyToReceiveDocument

public
boolean
True when the element is connected and ready to receive its GraphQL document

Methods

onData

publicOptional callback for when a query is completed.

Parameters

data

Data<D>
the query data.

Returns

void

onError

publicOptional callback for when an error occurs.

Parameters

error

Error
the error.

Returns

void

refetch

publicUpdate the variables of this observable query, and fetch the new results.

Parameters

variables

Variables<D, V>
The new set of variables. If there are missing variables, the previous values of those variables will be used..

Returns

Promise<ApolloQueryResult<Data<D>>>
Property Type Description
data Data<D> If the query resolved, the data.
error ApolloError If the query rejected, the error.
errors readonly GraphQLError[] If the query returned partials results, and some were errors, the list of errors.
loading boolean Whether the operation is in-flight.
partial boolean Whether the query returned partial data.
networkStatus NetworkStatus See NetworkStatus.

shouldSubscribe

publicDetermines whether the element should attempt to subscribe i.e. begin querying Override to prevent subscribing unless your conditions are met

Parameters

options

Partial<SubscriptionOptions<Variables<D, V>, Data<D>>>
Property Type Description
query DocumentNode See query
variables Variables<D, V> See variables
fetchPolicy FetchPolicy See fetchPolicy
errorPolicy ErrorPolicy See errorPolicy
context Record<string, unknown> Context object passed through the link execution chain.

Returns

boolean

subscribe

publicResets the internal state of the query and subscribes.

Parameters

params

Partial<SubscriptionOptions<Variables<D, V>, Data<D>>>
Property Type Description
query DocumentNode See query
variables Variables<D, V> See variables
fetchPolicy FetchPolicy See fetchPolicy
errorPolicy ErrorPolicy See errorPolicy
context Record<string, unknown> Context object passed through the link execution chain.

Returns

Subscription

subscribeToMore

public

Lets you pass a GraphQL subscription and updateQuery function to subscribe to more updates for your query.

The updateQuery parameter is a function that takes the previous query data, then a { subscriptionData: TSubscriptionResult } object, and returns an object with updated query data based on the new results.

Parameters

options

SubscribeToMoreOptions<Data<D>, TSubscriptionVariables, TSubscriptionData>

Returns

void | (() => void)

executeQuery

publicExecutes a Query once and updates the component with the result

Parameters

params

Partial<QueryOptions<Variables<D, V>, Data<D>>> | undefined
Option Type Description
query DocumentNode A GraphQL document that consists of a single query to be sent down to the server.
variables Variables<D, V> A map going from variable name to variable value, where the variables are used within the GraphQL query.
fetchPolicy FetchPolicy Specifies the fetchPolicy to be used for this query.
errorPolicy ErrorPolicy Specifies the ErrorPolicy to be used for this query.
context Record<string, unknown> Context object passed through the link execution chain.

Returns

Promise<ApolloQueryResult<Data<D>>>
Property Type Description
data Data<D> If the query resolved, the data.
error ApolloError If the query rejected, the error.
errors readonly GraphQLError[] If the query returned partials results, and some were errors, the list of errors.
loading boolean Whether the operation is in-flight.
partial boolean Whether the query returned partial data.
networkStatus NetworkStatus See NetworkStatus.

fetchMore

public

Exposes the ObservableQuery#fetchMore method. https://www.apollographql.com/docs/react/api/core/ObservableQuery/#ObservableQuery.fetchMore

The optional updateQuery parameter is a function that takes the previous query data, then a { subscriptionData: TSubscriptionResult } object, and returns an object with updated query data based on the new results.

The optional variables parameter is an optional new variables object.

Parameters

params

Partial<FetchMoreParams<D, V>> | undefined
Option Type Description
query DocumentNode Query to fetch, defaults to this.query
updateQuery Function Function to determine how to update the cache when the query resolves. (deprecated - use field policies instead)
variables Variables<D, V> Query variables
context Record<string, unknown> Context object passed through the link execution chain.

Returns

Promise<ApolloQueryResult<D>>
Property Type Description
data Data<D> If the query resolved, the data.
error ApolloError If the query rejected, the error.
errors readonly GraphQLError[] If the query returned partials results, and some were errors, the list of errors.
loading boolean Whether the operation is in-flight.
partial boolean Whether the query returned partial data.
networkStatus NetworkStatus See NetworkStatus.

Events

apollo-query-result

CustomEvent<ApolloQueryResult<Data<D>>>
The query resolved

apollo-error

CustomEvent<ApolloError>
The query rejected

apollo-element-connected

ApolloElementEvent
The element connected to the DOM

apollo-element-disconnected

ApolloElementEvent
The element disconnected from the DOM

Private Methods

documentChanged

protectedLifecycle callback that reacts to changes in the GraphQL document

Parameters

document

ComponentDocument<D, V> | null

Returns

void

variablesChanged

protectedLifecycle callback that reacts to changes in the operation variables

Parameters

variables

Variables<D, V> | null

Returns

void

Common interface for subscription elements

See ApolloElementInterface for more information on events

Properties

documentType

static(read-only)
'document'|'query'|'mutation'|'subscription'

controller

public
ApolloController<D, V>

data

public
Data<D> | null
Latest Data.Latest subscription data.

variables

public
Variables<D, V> | null
Subscription variables.

An object map from variable name to variable value, where the variables are used within the GraphQL subscription.

Setting variables will initiate the subscription, unless noAutoSubscribe is also set.

subscription

public
ComponentDocument<D, V> | null
A GraphQL document containing a single subscription.

canAutoSubscribe

public(read-only)
boolean
Flags an element that’s ready and able to auto subscribe

fetchPolicy

public
string | undefined
Specifies the FetchPolicy to be used for this subscription.

pollInterval

public
number | undefined
The time interval (in milliseconds) on which this subscription should be refetched from the server.

noAutoSubscribe

public
boolean
If true, the element will not begin querying data until you manually call subscribe

shouldResubscribe

public
boolean | ((options: SubscriptionDataOptions<Data<D>, Variables<D, V>>) => boolean)
Determines if your subscription should be unsubscribed and subscribed again.

skip

public
boolean
If true, the query will be skipped entirely

client

public
ApolloClient | null
The Apollo Client instance.

document

public
ComponentDocument<D, V> | null
Operation document.GraphQL operation document i.e. query, subscription, or mutation. Must be a parsed GraphQL DocumentNode, so use graphql-tag.

error

public
Error | null
Latest error

errors

public
readonly GraphQLError[]
Latest errors

loading

public
boolean
Whether a request is in flight.

context

public
Record<string, unknown> | undefined
Context passed to the link execution chain.

errorPolicy

public
ErrorPolicy | undefined
Error Policy for the operation.

Much like fetchPolicy, errorPolicy allows you to control how GraphQL errors from the server are sent to your UI code. By default, the error policy treats any GraphQL Errors as network errors and ends the request chain. It doesn’t save any data in the cache, and renders your UI with the error property set to an ApolloError. By changing this policy per request, you can adjust how GraphQL Errors are managed by your UI. The possible options for errorPolicy are:

  • none (default): any errors from the request are treated like runtime errors and the observable is stopped (XXX this is default to lower breaking changes going from AC 1.0 => 2.0)
  • ignore: errors from the request do not stop the observable, but also don’t call next
  • all: errors are treated like data and will notify observables

readyToReceiveDocument

public
boolean
True when the element is connected and ready to receive its GraphQL document

Methods

onSubscriptionData

publicCallback for when data is updated

Parameters

_result

OnSubscriptionDataParams<Data<D>>

Returns

void

onSubscriptionComplete

publicCallback for when subscription completes.

Returns

void

onError

publicCallback for when error is updated

Parameters

error

Error

Returns

void

subscribe

publicResets the subscription and subscribes.

Parameters

params

Partial<SubscriptionDataOptions<D, V>>
Option Type Description
client ApolloClient Apollo Client to use for the subscription.
context Record<string, unknown> Context object passed through the link execution chain.
errorPolicy ErrorPolicy Error policy to use for the subscription. See errorPolicy
fetchPolicy FetchPolicy See fetchPolicy
shouldResubscribe boolean Boolean, or a predicate function of SubscriptionDataOptions that determines if your subscription should be unsubscribed and subscribed again
skip boolean If skip is true, the subscription will be skipped entirely.
subscription DocumentNode GraphQL document with a single subscription.
variables Variables<D, V> An object containing all of the variables your subscription needs to execute.

Returns

void

cancel

publicCancels and clears the subscription

Returns

void

shouldSubscribe

publicDetermines whether the element should attempt to subscribe automatically Override to prevent subscribing unless your conditions are met

Parameters

options

Partial<SubscriptionOptions<Variables<D, V>, Data<D>>>
Property Type Description
query DocumentNode See query
variables Variables<D, V> See variables
fetchPolicy FetchPolicy See fetchPolicy
errorPolicy ErrorPolicy See errorPolicy
context Record<string, unknown> Context object passed through the link execution chain.

Returns

boolean

Events

apollo-subscription-result

ApolloSubscriptionResultEvent
The subscription updated

apollo-error

CustomEvent<ApolloError>
The subscription produced an error

apollo-element-connected

ApolloElementEvent
The element connected to the DOM

apollo-element-disconnected

ApolloElementEvent
The element disconnected from the DOM

Private Methods

documentChanged

protectedLifecycle callback that reacts to changes in the GraphQL document

Parameters

document

ComponentDocument<D, V> | null

Returns

void

variablesChanged

protectedLifecycle callback that reacts to changes in the operation variables

Parameters

variables

Variables<D, V> | null

Returns

void

Exports

js CustomElement from types.js

js ControllerHost from types.js

js ApolloElementElement from types.js

js ApolloMutationElement from types.js

js ApolloQueryElement from types.js

js ApolloSubscriptionElement from types.js

js GraphQLError from types.js