import { QueryClient, QueryClientProvider, createMutationController, createQueryController, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { worker } from './mocks' import { todosMutations, todosQueries } from './services/todos/queries' const queryClient = new QueryClient() class AutoRefetchingQueryProvider extends QueryClientProvider { constructor() { super() this.client = queryClient } } class AutoRefetchingExample extends LitElement { static properties = { intervalMs: { state: true }, value: { state: true }, } private intervalMs = 1000 private value = '' private readonly todos = createQueryController(this, () => ({ ...todosQueries.list(), // Refetch the data every second refetchInterval: this.intervalMs, })) private readonly addMutation = createMutationController(this, () => ({ ...todosMutations.create(), onSuccess: (_data, _variables, _onMutateResult, { client }) => client.invalidateQueries({ queryKey: todosQueries.all() }), })) private readonly clearMutation = createMutationController(this, () => ({ ...todosMutations.deleteAll(), onSuccess: (_data, _variables, _onMutateResult, { client }) => client.invalidateQueries({ queryKey: todosQueries.all() }), })) protected override createRenderRoot(): HTMLElement | DocumentFragment { return this } private submitForm(event: SubmitEvent) { event.preventDefault() this.addMutation.mutate(this.value, { onSuccess: () => { this.value = '' }, }) } render() { const { status, data, error, isFetching } = this.todos() if (status === 'pending') return html`

Loading...

` if (status === 'error') return html`Error: ${error.message}` return html`

Auto Refetch with refetchInterval set to ${this.intervalMs}ms

This example is best experienced on your own machine, where you can open multiple tabs to the same localhost server and see your changes propagate between the two.

Todo List

(this.value = (event.currentTarget as HTMLInputElement).value)} />
` } } class AutoRefetchingApp extends LitElement { protected override createRenderRoot(): HTMLElement | DocumentFragment { return this } render() { return html` ` } } customElements.define( 'auto-refetching-query-provider', AutoRefetchingQueryProvider, ) customElements.define('auto-refetching-example', AutoRefetchingExample) worker.start({ onUnhandledRequest: 'bypass' }).then(() => { customElements.define('auto-refetching-app', AutoRefetchingApp) })