Open History to see the last commit
1import { QueryClient, QueryClientProvider } from '@tanstack/lit-query'
2import { LitElement, html } from 'lit'
3import './post-list'
4import './post-detail'
5import type { QueryKey } from '@tanstack/lit-query'
6β
7// Define a default query function that will receive the query key
8const defaultQueryFn = async ({ queryKey }: { queryKey: QueryKey }) => {
9 const response = await fetch(
10 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
11 )
12 if (!response.ok) throw new Error('Failed to fetch data')
13 return await response.json()
14}
15β
16// provide the default query function to your app with defaultOptions
17const queryClient = new QueryClient({
18 defaultOptions: {
19 queries: {
20 queryFn: defaultQueryFn,
21 },
22 },
23})
24β
25class DefaultQueryFunctionQueryProvider extends QueryClientProvider {
26 constructor() {
27 super()
28 this.client = queryClient
29 }
30}
31β
32class DefaultQueryFunctionApp extends LitElement {
33 static properties = {
34 postId: { state: true },
35 }
36β
37 private postId = -1
38β
39 protected override createRenderRoot(): HTMLElement | DocumentFragment {
40 return this
41 }
42β
43 private setPostId(event: CustomEvent<number>) {
44 this.postId = event.detail
45 }
46β
47 render() {
48 return html`
49 <default-query-function-query-provider>
50 <p>
51 As you visit the posts below, you will notice them in a loading state
52 the first time you load them. However, after you return to this list
53 and click on any posts you have already visited again, you will see
54 them load instantly and background refresh right before your eyes!
55 <strong>
56 (You may need to throttle your network speed to simulate longer
57 loading sequences)
58 </strong>
59 </p>
60 ${
61 this.postId > -1
62 ? html`<post-detail
63 .postId=${this.postId}
64 @set-post-id=${this.setPostId}
65 ></post-detail>`
66 : html`<post-list @set-post-id=${this.setPostId}></post-list>`
67 }
68 </default-query-function-query-provider>
69 `
70 }
71}
72β
73customElements.define(
74 'default-query-function-query-provider',
75 DefaultQueryFunctionQueryProvider,
76)
77customElements.define('default-query-function-app', DefaultQueryFunctionApp)