ApolloQueryController

Query Controller for Apollo Elements

ApolloQueryController gets data from your GraphQL server. Pass it a GraphQL query, and any options you choose, and it will update its host when it’s state (e.g. data, error, or loading) changes.

The (optional) third argument to the constructor is an ApolloQueryControllerOptions object, with all properties optional. Pass a fetchPolicy, or variables to customize the query, noAutoSubscribe: false or a shouldSubscribe predicate function to prevent automatically fetching data, or onData/onError callbacks to run side-effects when the query resolves or errors.

Apollo Elements controllers are not limited to Lit. Use them with any object that implements the ReactiveControllerHost interface. See ControllerHostMixin for an example.

import '@apollo-elements/components/apollo-client';
import { ApolloQueryController } from '@apollo-elements/core';
import { customElement } from 'lit/decorators.js';
import { html, LitElement } from 'lit';
import { classMap } from 'lit/directives/class-map.js';
import { ProfileQuery } from './Profile.query.graphql.js';
import style from './profile-home.css.js';

@customElement('profile-home')
class ProfileHome extends LitElement {
  static ids = [1,2,3];

  static styles = style;

  profile = new ApolloQueryController(this, ProfileQuery, {
    variables: { id: 1 }
  });

  radio(id) {
    const astronaut = this.profile.data?.profile;
    return html`
      <label> <input id=${id} type=radio name=id value=${id}
               ?checked=${astronaut?.id == id}
               @change=${this.onChange}/> ${id} </label>`;
  }

  onChange(event) { this.profile.variables = { id: event.target.value } }

  render() {
    const { data, loading } = this.profile ?? {};
    const astronaut = data?.profile;
    return html`
      <form><legend>Crew ID</legend>${ProfileHome.ids.map(this.radio, this)}</form>
      <article class=${classMap({ loading })}>
        <img .src=${astronaut?.picture} alt=""/>
        <figure>
          <blockquote>${astronaut?.quote}</blockquote>
          <figcaption>- ${astronaut?.name}, ${astronaut?.position}</figcaption>
        </figure>
      </article>
    `;
  }
}

Properties

options

ApolloControllerOptions<D, V>
Options to customize the query and to interface with the controller.
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

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.

partial

boolean
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.

query

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

canAutoSubscribe

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

called

boolean

data

Data<D> | null
Latest data for the operation, or null.

error

Error | null
Latest error from the operation, or null.

errors

readonly GraphQLError[]
Latest errors from the operation, or [].

loading

boolean
Whether a request is in-flight.

client

ApolloClient | null
The ApolloClient instance for this controller.

document

ComponentDocument<D, V> | null
The GraphQL document for the operation.

variables

Variables<D, V> | null
Variables for the operation.

Methods

hostConnected

initializes or reinitializes the query

Returns

void

hostDisconnected

Returns

void

refetch

publicasyncExposes the ObservableQuery#refetch method.

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.

subscribe

publicResets the observableQuery and subscribes.

Parameters

params

Partial<WatchQueryOptions<Variables<D, V>, Data<D>>>
options for controlling how the subscription subscribes

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

publicasyncExecutes a Query once and updates the with the result

Parameters

params

Partial<QueryOptions<Variables<D, V>, Data<D>>>
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

publicasync

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<TD, TV>>
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<Data<TD>>>
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.

startPolling

publicStart polling this query

Parameters

ms

number
milliseconds to wait between fetches

Returns

void

stopPolling

publicStop polling this query

Returns

void

Events

apollo-controller-connected

ApolloControllerConnectedEvent
The controller’s host connected to the DOM.

apollo-controller-disconnected

ApolloControllerDisconnectedEvent
The controller’s host disconnected from the DOM.

Private Properties

observableQuery

private
ObservableQuery<Data<D>, Variables<D, V>> | undefined

pollingInterval

private
number | undefined

#hasDisconnected

private
boolean

#lastQueryDocument

private
DocumentNode | undefined

#options

private
ApolloControllerOptions<D, V>
Option Type Description
client ApolloClient<NormalizedCacheObject> The ApolloClient instance for the controller.
variables Variables<D, V> Variables for the operation.
context any Context passed to the link execution chain.
errorPolicy ErrorPolicy the error policy for the operation
hostElement HTMLElement When provided, the controller will fall back to this element to fire events

#client

private
ApolloClient | null

#document

private
ComponentDocument<D, V> | null

emitter

protected
EventTarget
The event emitter to use when firing events, usually the host element.

Private Methods

shouldSubscribe

private

Parameters

opts

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

Returns

boolean

canSubscribe

privateDetermines whether the element is able to automatically subscribe

Parameters

options

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

Returns

boolean

watchQuery

private

Creates an instance of ObservableQuery with the options provided by the element.

  • context Context to be passed to link execution chain
  • errorPolicy Specifies the ErrorPolicy to be used for this query
  • fetchPolicy Specifies the FetchPolicy to be used for this query
  • fetchResults Whether or not to fetch results
  • metadata Arbitrary metadata stored in the store with this query. Designed for debugging, developer tools, etc.
  • notifyOnNetworkStatusChange Whether or not updates to the network status should trigger next on the observer of this query
  • pollInterval The time interval (in milliseconds) on which this query should be refetched from the server.
  • query A GraphQL document that consists of a single query to be sent down to the server.
  • variables A map going from variable name to variable value, where the variables are used within the GraphQL query.

Parameters

params

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

Returns

ObservableQuery<Data<D>, Variables<D, V>>

nextData

private

Parameters

result

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.

Returns

void

nextError

private

Parameters

error

Error

Returns

void

clientChanged

protectedcallback for when the Apollo client changes.

Parameters

client

ApolloClient | null

Returns

void

documentChanged

protectedcallback for when the GraphQL document changes.

Parameters

doc

ComponentDocument<D, V> | null

Returns

void

variablesChanged

protectedcallback for when the GraphQL variables change.

Parameters

variables

Variables<D, V>

Returns

void

optionsChanged

protectedcallback for when the options change.

Parameters

options

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

Returns

void

notify

protectedrequests an update on the host with the provided properties.

Parameters

properties

Record<string, unknown>

Returns

void

init

protectedAssigns the controller’s variables and GraphQL document.

Parameters

document

ComponentDocument<D, V> | null

Returns

void

Exports

js ApolloQueryController from apollo-query-controller.js