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>
`;
}
}
import { css } from 'lit';
export default css`
:host { display: block; }
.loading { opacity: 0.5; filter: grayscale(100%); }
img { width: 100%; height: auto; background: lightgrey; min-height: 295px; }
article { width: 100%; }
figure { margin: 0; }
form {
display: grid;
grid-template: 40px / max-content repeat(3, 40px);
place-items: center;
}
`;
<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';
type Data = { profile: { id: number; name: string; picture: string; quote: string; } };
type Variables = { id: number; };
export const ProfileQuery: TypedDocumentNode<Data, Variables> = gql`
query ProfileQuery($id: ID) {
profile(id: $id) {
id
name
position
picture
quote
}
}
`;
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',
position: 'Commander',
picture: 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Neil_Armstrong_pose.jpg/1024px-Neil_Armstrong_pose.jpg?1623601441968',
quote: 'That’s one small step for a man, one giant leap for mankind.',
},
{
id: 2,
name: 'Buzz',
position: 'Lunar Module Pilot',
picture: 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Buzz_Aldrin.jpg/1024px-Buzz_Aldrin.jpg?1623601483170',
quote: 'Those footprints belong to each and every one of you, to all mankind.',
},
{
id: 3,
name: 'Michael',
position: 'Command Module Pilot',
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',
quote: 'It’s human nature to stretch, to go, to see, to understand. Exploration is not a choice, really; it’s an imperative.',
},
];
const schema = makeExecutableSchema({
typeDefs: `
type User {
id: ID
name: String
picture: String
position: String
quote: String
}
type Query {
profile(id: ID): User
}
`,
resolvers: {
Query: {
async profile(_, { id }) {
await new Promise(r => setTimeout(r, Math.random() * 1000));
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.
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
(read-only)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.
options
inherited from ApolloControllerApolloControllerOptions<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 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. |
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. |
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 ApolloControllerinitializes or reinitializes the query
Returns
void
hostDisconnected
inherited from ApolloControllerReturns
void
Events
Name | Type | Description |
---|---|---|
apollo-controller-connected |
|
The controller's host connected to the DOM. |
apollo-controller-disconnected |
|
The controller's host disconnected from the DOM. |
Private API
Private Properties
observableQuery
ObservableQuery<Data<D>, Variables<D, V>> | undefined
#lastQueryDocument
DocumentNode | undefined
#hasDisconnected
boolean
#client
inherited from ApolloControllerApolloClient<NormalizedCacheObject> | null
#document
inherited from ApolloControllerComponentDocument<D> | null
#options
inherited from ApolloControllerApolloControllerOptions<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 |
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>>
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
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
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
[update]
inherited from ApolloControllerrequests an update on the host.
Parameters
properties
Record<string, unknown>
Returns
void
clientChanged
inherited from ApolloControllercallback for when the Apollo client changes.
Parameters
client
ApolloClient<NormalizedCacheObject> | null
Returns
void
documentChanged
inherited from ApolloControllercallback for when the GraphQL document changes.
Parameters
doc
ComponentDocument<D> | null
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
optionsChanged
inherited from ApolloControllercallback 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
variablesChanged
inherited from ApolloControllercallback for when the GraphQL variables change.
Parameters
variables
Variables<D, V>
Returns
void
Exports
import { ApolloQueryController } from '@apollo-elements/core/apollo-query-controller';