Atomico: useQuery
Apollo useQuery
hook for web components.
Demo
import { useQuery, c, html, css } from '@apollo-elements/atomico';
import { LaunchesQuery } from './Launches.query.graphql.js';
import { client } from './client.js';
function Launches() {
const { data } = useQuery(LaunchesQuery, { client, variables: { limit: 3 } });
const launches = data?.launchesPast ?? [];
return html`
<host shadowDom>
<ol>${launches.map(x => html`
<li>
<article>
<span>${x.mission_name}</span>
<img src=${x.links.mission_patch_small} alt="Badge" role="presentation"/>
</article>
</li>`)}
</ol>
</host>
`;
}
Launches.styles = css`
:host {
--image-size: 40px;
}
li img {
height: var(--image-size);
width: auto;
}
li article {
height: var(--image-size);
display: flex;
justify-content: space-between;
}
`;
customElements.define('spacex-launches', c(Launches));
<script type="module" src="launches.js"></script>
<apollo-client uri="https://api.spacex.land/graphql">
<spacex-launches></spacex-launches>
</apollo-client>
import { gql, TypedDocumentNode } from '@apollo/client/core';
interface Launch {
mission_name: string;
links: {
mission_patch_small: string;
};
}
interface Data {
launchesPast: Launch[];
}
interface Variables {
limit: number;
}
export const LaunchesQuery: TypedDocumentNode<Data, Variables> = gql`
query LaunchesQuery($limit: Int) {
launchesPast(limit: $limit) {
id
mission_name
links { mission_patch_small }
}
}
`;
;
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client/core';
export const client = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({ uri: 'https://api.spacex.land/graphql' }),
});
Read the query component guides for more examples and tips.
useQuery
Parameters
query
ComponentDocument<D, V>
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
ApolloQueryController<D, V>
Exports
import { useQuery } from '@apollo-elements/atomico/useQuery';