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 { ApolloQueryController } from '@apollo-elements/core';
import { customElement } from 'lit/decorators.js';
import { css, html, LitElement } from 'lit';
import { classMap } from 'lit/directives/class-map.js';
import { ProfileQuery } from './Profile.query.graphql.js';
@customElement('profile-home')
class ProfileHome extends LitElement {
static styles = css`
img { height: 200px; width: auto; }
`;
profile = new ApolloQueryController(this, ProfileQuery, {
variables: { id: 1 }
});
render() {
return html`
<h2>User ID Variable</h2>
<input id="1" type="radio" name="id" value="1" @change="${this.onChange}"/>
<label for="1">1</label>
<input id="2" type="radio" name="id" value="2" @change="${this.onChange}"/>
<label for="2">2</label>
<input id="3" type="radio" name="id" value="3" @change="${this.onChange}"/>
<label for="3">3</label>
<header class=${classMap({ loading: this.profile?.loading })}>
<h1>Welcome, ${this.profile.data?.profile?.name}</h1>
</header>
<img .src=${this.profile.data?.profile?.picture} alt=""/>
`;
}
onChange(event) {
this.profile.variables = { id: event.target.value }
}
}
<script type="module" src="profile-home.js"></script>
<script type="module" src="client.js"></script>
<apollo-client>
<profile-home></profile-home>
</apollo-client>
import { gql, TypedDocumentNode } from '@apollo/client/core';
export const ProfileQuery: TypedDocumentNode<{
profile: {
name: string;
picture: string;
}
}> = gql`
query ProfileQuery($id: ID) {
profile(id: $id) {
name
picture
}
}
`;
import { ApolloClient, InMemoryCache } from '@apollo/client/core';
import { SchemaLink } from '@apollo/client/link/schema';
import { makeExecutableSchema } from '@graphql-tools/schema';
const USERS = [
{ id: 1, name: 'Neil', picture: 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Neil_Armstrong_pose.jpg/1024px-Neil_Armstrong_pose.jpg?1623601441968' },
{ id: 2, name: 'Buzz', picture: 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Buzz_Aldrin.jpg/1024px-Buzz_Aldrin.jpg?1623601483170' },
{ id: 3, name: 'Michael', picture: 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Michael_Collins_%28S69-31742%2C_restoration%29.jpg/1024px-Michael_Collins_%28S69-31742%2C_restoration%29.jpg?1623601522599' },
];
const schema = makeExecutableSchema({
typeDefs: `
type User {
id: ID
name: String
picture: String
}
type Query {
profile(id: ID): User
}
`,
resolvers: {
Query: {
async profile(_, { id }) {
return USERS.find(x => x.id == parseInt(id));
}
},
}
});
document.querySelector('apollo-client')
.client = new ApolloClient({
cache: new InMemoryCache(),
link: new SchemaLink({ schema }),
});
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.
options
ApolloQueryControllerOptions<D, V>
Options to customize the query and to interface with the controller.
All properties are optional
Property | 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 |
If true, the element will not begin querying data until you manually call subscribe |
onData | (data: Data<D>) => void |
Optional callback for when a query resolves. |
onError | (error: Error) => void |
Optional callback for when an error occurs. |
networkStatus
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.
canAutoSubscribe
boolean
Flags an element that's ready and able to auto-subscribe
called
inherited from ApolloControllerboolean
client
inherited from ApolloControllerApolloClient<NormalizedCacheObject> | null
The ApolloClient
instance for this controller.
data
inherited from ApolloControllerData<D> | null
Latest data for the operation, or null
.
document
inherited from ApolloControllerComponentDocument<D> | null
The GraphQL document for the operation.
error
inherited from ApolloControllerApolloError | null
Latest error from the operation, or null
.
errors
inherited from ApolloControllerreadonly GraphQLError[]
Latest errors from the operation, or []
.
loading
inherited from ApolloControllerboolean
Whether a request is in-flight.
variables
inherited from ApolloControllerVariables<D, V> | null
Variables for the operation.
Methods
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
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
stopPolling
Stop polling this query
Returns
void
startPolling
Start polling this query
Parameters
ms
number
milliseconds to wait between fetches
Returns
void
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. |
hostDisconnected
Returns
void
hostConnected
initializes or reinitializes the query
Returns
void
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 | TypedDocumentNode`{lang=ts} |
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. |
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 | TypedDocumentNode`{lang=ts} |
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. |
Private API
Private Properties
pollingInterval
number
observableQuery
ObservableQuery<Data<D>, Variables<D, V>>
#lastQueryDocument
DocumentNode
#hasDisconnected
boolean
#client
inherited from ApolloControllerApolloClient<NormalizedCacheObject> | null
#document
inherited from ApolloControllerComponentDocument<D> | null
#options
inherited from ApolloControllerApolloControllerOptions<D, V>
emitter
inherited from ApolloControllerEventTarget
The event emitter to use when firing events, usually the host element.
Private Methods
watchQuery
Creates an instance of ObservableQuery with the options provided by the element.
context
Context to be passed to link execution chainerrorPolicy
Specifies the ErrorPolicy to be used for this queryfetchPolicy
Specifies the FetchPolicy to be used for this queryfetchResults
Whether or not to fetch resultsmetadata
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 querypollInterval
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>>
variablesChanged
Parameters
variables
Variables<D, V>
Returns
void
shouldSubscribe
Parameters
opts
Partial<SubscriptionOptions<Variables<D, V>, Data<D>>>
Property | Type | Description |
---|---|---|
query | `DocumentNode | TypedDocumentNode`{lang=ts} |
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
nextError
Parameters
error
ApolloError
Returns
void
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
documentChanged
Parameters
doc
ComponentDocument<D> | null
Returns
void
clientChanged
Returns
void
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 | TypedDocumentNode`{lang=ts} |
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
[update]
inherited from ApolloControllerrequests an update on the host.
Parameters
properties
Record<string, unknown>
Returns
void
init
inherited from ApolloControllerAssigns the controller's variables and GraphQL document.
Parameters
document
ComponentDocument<D> | null
Returns
void
notify
inherited from ApolloControllerNotifies about updated properties.
Parameters
keys
(keyof this)[]
Returns
void
Exports
import { ApolloQueryController } from '@apollo-elements/core/apollo-query-controller';