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>| 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.
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.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.fetchMore: Indicates that fetchMore was called on this query and that the network request created is currently in flight.refetch: It means that refetch was called on a query and the refetch request is currently in flight.- Unused.
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.ready: No request is in flight for this query, and no errors happened. Everything is OK.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
booleanquery
ComponentDocument<D, V> | nullcanAutoSubscribe
public(read-only)booleancalled
booleandata
Data<D> | nullnull.error
Error | nullnull.errors
readonly GraphQLError[][].loading
booleanclient
ApolloClient | nullApolloClient instance for this controller.document
ComponentDocument<D, V> | nullvariables
Variables<D, V> | nullMethods
hostConnected
initializes or reinitializes the queryReturns
voidhostDisconnected
Returns
voidrefetch
publicasyncExposes theObservableQuery#refetch method.Parameters
variables
Variables<D, V>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>>>Returns
SubscriptionsubscribeToMore
publicLets 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) | voidexecuteQuery
publicasyncExecutes a Query once and updates the with the resultParameters
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
publicasyncExposes 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 queryParameters
ms
numberReturns
voidstopPolling
publicStop polling this queryReturns
voidEvents
apollo-controller-connected
ApolloControllerConnectedEventThe controller’s host connected to the DOM.apollo-controller-disconnected
ApolloControllerDisconnectedEventThe controller’s host disconnected from the DOM.
Private Properties
observableQuery
privateObservableQuery<Data<D>, Variables<D, V>> | undefinedpollingInterval
privatenumber | undefined#hasDisconnected
privateboolean#lastQueryDocument
privateDocumentNode | undefined#options
privateApolloControllerOptions<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
privateApolloClient | null#document
privateComponentDocument<D, V> | nullemitter
protectedEventTarget
Private Methods
shouldSubscribe
privateParameters
opts
Partial<WatchQueryOptions<Variables<D, V>, Data<D>>>Returns
booleancanSubscribe
privateDetermines whether the element is able to automatically subscribeParameters
options
Partial<WatchQueryOptions<Variables<D, V>, Data<D>>>Returns
booleanwatchQuery
privateCreates an instance of ObservableQuery with the options provided by the element.
contextContext to be passed to link execution chainerrorPolicySpecifies the ErrorPolicy to be used for this queryfetchPolicySpecifies the FetchPolicy to be used for this queryfetchResultsWhether or not to fetch resultsmetadataArbitrary metadata stored in the store with this query. Designed for debugging, developer tools, etc.notifyOnNetworkStatusChangeWhether or not updates to the network status should trigger next on the observer of this querypollIntervalThe time interval (in milliseconds) on which this query should be refetched from the server.queryA GraphQL document that consists of a single query to be sent down to the server.variablesA 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
privateParameters
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
voidnextError
privateParameters
error
ErrorReturns
voidclientChanged
protectedcallback for when the Apollo client changes.Parameters
client
ApolloClient | nullReturns
voiddocumentChanged
protectedcallback for when the GraphQL document changes.Parameters
doc
ComponentDocument<D, V> | nullReturns
voidvariablesChanged
protectedcallback for when the GraphQL variables change.Parameters
variables
Variables<D, V>Returns
voidoptionsChanged
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
voidnotify
protectedrequests an update on the host with the provided properties.Parameters
properties
Record<string, unknown>Returns
voidinit
protectedAssigns the controller’s variables and GraphQL document.Parameters
document
ComponentDocument<D, V> | nullReturns
voidExports
js ApolloQueryController from apollo-query-controller.js