Open History to see the last commit
1import { Router } from '@lit-labs/router'
2import { QueryClientProvider, noop, onlineManager } from '@tanstack/lit-query'
3import { persistQueryClient } from '@tanstack/query-persist-client-core'
4import { LitElement, html } from 'lit'
5import { worker } from './mocks'
6import { persister, queryClient } from './queryClient'
7import { moviesQueries } from './services/movies/queries'
8import './movie-list-view'
9import './movie-detail-view'
10β
11class OfflineQueryProvider extends QueryClientProvider {
12 constructor() {
13 super()
14 this.client = queryClient
15 }
16}
17β
18class OfflineApp extends LitElement {
19 static properties = {
20 isOnline: { state: true },
21 }
22β
23 private isOnline = onlineManager.isOnline()
24 private unsubscribeOnline: () => void = noop
25β
26 private readonly router = new Router(this, [
27 {
28 path: '/',
29 render: () => html`<movie-list-view></movie-list-view>`,
30 },
31 {
32 path: '/:movieId',
33 enter: async ({ movieId = '' }) => {
34 if (
35 !queryClient.getQueryData(moviesQueries.detail(movieId).queryKey) &&
36 // do not load if we are offline because it returns a promise that is pending until we go online again
37 // we just let the movie-detail-view element handle it
38 onlineManager.isOnline()
39 ) {
40 await queryClient.query(moviesQueries.detail(movieId)).catch(noop)
41 }
42 return true
43 },
44 render: ({ movieId }) =>
45 html`<movie-detail-view .movieId=${movieId}></movie-detail-view>`,
46 },
47 ])
48β
49 override connectedCallback() {
50 super.connectedCallback()
51 this.unsubscribeOnline = onlineManager.subscribe((isOnline) => {
52 this.isOnline = isOnline
53 })
54 }
55β
56 override disconnectedCallback() {
57 super.disconnectedCallback()
58 this.unsubscribeOnline()
59 }
60β
61 protected override createRenderRoot(): HTMLElement | DocumentFragment {
62 return this
63 }
64β
65 render() {
66 return html`
67 <offline-query-provider>
68 <div style="padding: 16px">
69 <button
70 type="button"
71 @click=${() => onlineManager.setOnline(!this.isOnline)}
72 >
73 ${this.isOnline ? 'Go offline' : 'Go online'}
74 </button>
75 ${this.router.outlet()}
76 </div>
77 </offline-query-provider>
78 `
79 }
80}
81β
82customElements.define('offline-query-provider', OfflineQueryProvider)
83β
84worker.start().then(async () => {
85 const [, restorePromise] = persistQueryClient({ queryClient, persister })
86 await restorePromise
87 // resume mutations after initial restore from localStorage was successful
88 queryClient.resumePausedMutations().then(() => {
89 queryClient.invalidateQueries()
90 })
91 customElements.define('offline-app', OfflineApp)
92})