Apollo Elements Apollo Elements Guides API Blog Toggle darkmode

Controllers: ApolloQueryController

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

query

ComponentDocument<D> | null

A GraphQL document containing a single query.

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.

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.

public

canAutoSubscribe

(read-only)
boolean

Flags an element that's ready and able to auto-subscribe

called

inherited from ApolloController
boolean

client

inherited from ApolloController
ApolloClient<NormalizedCacheObject> | null

The ApolloClient instance for this controller.

data

inherited from ApolloController
Data<D> | null

Latest data for the operation, or null.

document

inherited from ApolloController
ComponentDocument<D> | null

The GraphQL document for the operation.

error

inherited from ApolloController
ApolloError | null

Latest error from the operation, or null.

errors

inherited from ApolloController
readonly GraphQLError[]

Latest errors from the operation, or [].

loading

inherited from ApolloController
boolean

Whether a request is in-flight.

options

inherited from ApolloController
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

variables

inherited from ApolloController
Variables<D, V> | null

Variables for the operation.

Methods

public

subscribeToMore

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
public

subscribe

Resets the observableQuery and subscribes.

Parameters

params

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

options for controlling how the subscription subscribes

Returns

ZenObservable.Subscription
public

stopPolling

Stop polling this query

Returns

void
public

startPolling

Start polling this query

Parameters

ms

number

milliseconds to wait between fetches

Returns

void
public async

refetch

Exposes 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.
public async

fetchMore

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>>
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<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.
public async

executeQuery

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

hostConnected

inherited from ApolloController

initializes or reinitializes the query

Returns

void

hostDisconnected

inherited from ApolloController

Returns

void

Events

Name Type Description
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 API

Private Properties

private

pollingInterval

number | undefined
private

observableQuery

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

#lastQueryDocument

DocumentNode | undefined
private

#hasDisconnected

boolean
private

#client

inherited from ApolloController
ApolloClient<NormalizedCacheObject> | null
private

#document

inherited from ApolloController
ComponentDocument<D> | null
private

#options

inherited from ApolloController
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
protected

emitter

inherited from ApolloController
EventTarget

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

Private Methods

private

watchQuery

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>>
private

shouldSubscribe

Parameters

opts

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
private

nextError

Parameters

error

ApolloError

Returns

void
private

nextData

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
private

canSubscribe

Determines whether the element is able to automatically subscribe

Parameters

options

Partial<SubscriptionOptions<Variables<D, V> | null, 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
private

[update]

inherited from ApolloController

requests an update on the host.

Parameters

properties

Record<string, unknown>

Returns

void
protected

clientChanged

inherited from ApolloController

callback for when the Apollo client changes.

Parameters

client

ApolloClient<NormalizedCacheObject> | null

Returns

void
protected

documentChanged

inherited from ApolloController

callback for when the GraphQL document changes.

Parameters

doc

ComponentDocument<D> | null

Returns

void
protected

init

inherited from ApolloController

Assigns the controller's variables and GraphQL document.

Parameters

document

ComponentDocument<D> | null

Returns

void
protected

notify

inherited from ApolloController

Notifies about updated properties.

Parameters

keys

(keyof this)[]

Returns

void
protected

optionsChanged

inherited from ApolloController

callback 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
protected

variablesChanged

inherited from ApolloController

callback for when the GraphQL variables change.

Parameters

variables

Variables<D, V>

Returns

void

Exports

import { ApolloQueryController } from '@apollo-elements/core/apollo-query-controller';