Components: apollo-query
<apollo-query>
lets you query GraphQL without writing any JavaScript. Import the custom element then write your template, query, and variables in HTML. The element class inherits from ApolloQueryInterface
This page has detailed API documentation for <apollo-query>
. See the <apollo-query>
HTML Element guide for a HOW-TO guide.
Live Demo
<apollo-client>
<apollo-query>
<script type="application/graphql" src="Friends.query.graphql"></script>
<template>
<link rel="stylesheet" href="Friends.css"/>
<h1>Friends</h1>
<p>Hello, {{ data.me.name }}. Here are your friends.</p>
<ul>
<template type="repeat" repeat="{{ data.friends ?? [] }}">
<li data-id="{{ item.id }}"
data-index="{{ index }}">
<figure>
<img .src="{{ item.picture }}" role="presentation">
<figcaption>{{ item.name }}</figcaption>
</figure>
</li>
</template>
</ul>
</template>
</apollo-query>
</apollo-client>
<script type="module" src="client.js"></script>
query Friends {
me { id name picture }
friends { id name picture }
}
ul {
margin: 0;
padding: 0;
list-style-type: none;
display: grid;
grid-template-columns: repeat(
auto-fit,
minmax(100px, auto)
);
}
figure { display: contents; }
img { width: 100px; height: auto; }
import { ApolloClient, InMemoryCache } from '@apollo/client/core';
import { SchemaLink } from '@apollo/client/link/schema';
import { makeExecutableSchema } from '@graphql-tools/schema';
import '@apollo-elements/components';
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 SortOrder {
dir: String
by: String
}
type Query {
me: User
friends: [User]
}
`,
resolvers: {
Query: {
async me() {
return USERS.find(x => x.id === 1);
},
async friends() {
return USERS.filter(x => x.id !== 1);
}
},
}
});
document.querySelector('apollo-client')
.client = new ApolloClient({
cache: new InMemoryCache(),
link: new SchemaLink({ schema }),
});
Render a GraphQL query to the DOM
Examples
Attributes
'no-shadow'
inherited from StampinoRenderBoolean|string
When set, the element will render to a <div>
in its light DOM. If set with a string, the string will be the div's class name.
Properties
is
(read-only)string
returnPartialData
return-partial-databoolean | undefined
Opt into receiving partial results from the cache for queries that are not fully satisfied by the cache.
query
null | ComponentDocument<D, V>
A GraphQL document containing a single query.
pollInterval
poll-intervalnumber | undefined
The time interval (in milliseconds) on which this query should be refetched from the server.
partialRefetch
partial-refetchboolean | undefined
Set to retry any partial query results.
If true, perform a query refetch if the query result is marked as being partial, and the returned data is reset to an empty Object by the Apollo Client QueryManager (due to a cache miss).
The default value is false for backwards-compatibility's sake, but should be changed to true for most use-cases.
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>
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
notifyOnNetworkStatusChange
notify-on-network-status-changeboolean
Whether or not updates to the network status should trigger next on the observer of this query.
noAutoSubscribe
no-auto-subscribeboolean
When true, the component will not automatically subscribe to new data.
Call the subscribe()
method to do so.
nextFetchPolicy
next-fetch-policyWatchQueryFetchPolicy | NextFetchPolicyFunction<D, V> | undefined
Set to prevent subsequent network requests when the fetch policy is cache-and-network
or network-only
.
When someone chooses cache-and-network or network-only as their initial FetchPolicy, they often do not want future cache updates to trigger unconditional network requests, which is what repeatedly applying the cache-and-network or network-only policies would seem to imply. Instead, when the cache reports an update after the initial network request, it may be desirable for subsequent network requests to be triggered only if the cache result is incomplete. The nextFetchPolicy option provides a way to update options.fetchPolicy after the intial network request, without having to set options.
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.
fetchPolicy
fetch-policyWatchQueryFetchPolicy | undefined
The fetchPolicy for the query.
Determines where the client may return a result from. The options are:
cache-first
(default): return result from cache, fetch from network if cached result is not available.cache-and-network
: return result from cache first (if it exists), then return network result once it's available.cache-only
: return result from cache if available, fail otherwise.no-cache
: return result from network, fail if network call doesn't succeed, don't save to cachenetwork-only
: return result from network, fail if network call doesn't succeed, save to cachestandby
: only for queries that aren't actively watched, but should be available for refetch and updateQueries.
errorPolicy
error-policyErrorPolicy | undefined
Error Policy for the query.
errorPolicy determines the level of events for errors in the execution result. The options are:
none
(default): any errors from the request are treated like runtime errors and the observable is stopped (XXX this is default to lower breaking changes going from AC 1.0 => 2.0)ignore
: errors from the request do not stop the observable, but also don't callnext
all
: errors are treated like data and will notify observables
context
Record<string, any> | undefined
Context passed to the link execution chain.
canAutoSubscribe
boolean
Flags an element that's ready and able to auto subscribe
client
inherited from ApolloElementApolloClient<NormalizedCacheObject> | null
The Apollo Client instance.
controller
inherited from ApolloElementApolloController<D, V>
data
inherited from ApolloElementData<D> | null
Latest Data.
document
inherited from ApolloElementComponentDocument<D, V> | null
Operation document.
GraphQL operation document i.e. query, subscription, or mutation.
Must be a parsed GraphQL DocumentNode
error
inherited from ApolloElementError | ApolloError | null
Latest error
errors
inherited from ApolloElementreadonly GraphQLError[]
Latest errors
loading
inherited from ApolloElement loadingboolean
Whether a request is in flight.
readyToReceiveDocument
inherited from ApolloElementboolean
template
(read-only) inherited from StampinoRender templateHTMLTemplateElement | null
Template element to render. Can either be a light-DOM child of the element,
or referenced by ID with the template
attribute.
templateHandlers
inherited from StampinoRenderTemplateHandlers
variables
inherited from ApolloElementVariables<D, V> | null
Operation variables.
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
ObservableSubscription
stopPolling
Returns
void
startPolling
Parameters
ms
number
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. |
$
inherited from StampinoRenderquerySelector
within the render root.
Parameters
sel
string
Returns
E | null
$$
inherited from StampinoRenderquerySelectorAll
within the render root.
Parameters
sel
string
Returns
NodeListOf<E>
Private API
Private Methods
isQueryable
inherited from StampinoRenderParameters
node
Node
Returns
node is (ShadowRoot|Document)
createRenderRoot
inherited from StampinoRenderReturns
ShadowRoot|HTMLElement
getElementByIdFromRoot
inherited from StampinoRenderParameters
id
string|null
Returns
HTMLElement | null
getTemplateFromRoot
inherited from StampinoRenderReturns
HTMLTemplateElement | null
Exports
import '@apollo-elements/components/apollo-query';
import { ApolloQueryElement } from '@apollo-elements/components/apollo-query';