|
| 1 | +--- |
| 2 | +title: Quick Start |
| 3 | +id: quick-start |
| 4 | +--- |
| 5 | + |
| 6 | +The basic Lit app example to get started with TanStack `lit-store`. |
| 7 | + |
| 8 | +```ts |
| 9 | +import { LitElement, html } from 'lit' |
| 10 | +import { customElement, property } from 'lit/decorators.js' |
| 11 | +import { TanStackStoreSelector, createStore } from '@tanstack/lit-store' |
| 12 | + |
| 13 | +// You can instantiate a Store outside of Lit components too! |
| 14 | +export const store = createStore({ |
| 15 | + dogs: 0, |
| 16 | + cats: 0, |
| 17 | +}) |
| 18 | + |
| 19 | +type Animal = 'dogs' | 'cats' |
| 20 | + |
| 21 | +const updateState = (animal: Animal) => { |
| 22 | + store.setState((state) => ({ |
| 23 | + ...state, |
| 24 | + [animal]: state[animal] + 1, |
| 25 | + })) |
| 26 | +} |
| 27 | + |
| 28 | +// This will only re-render when `state[animal]` changes. If an unrelated |
| 29 | +// store property changes, it won't re-render. |
| 30 | +@customElement('animal-display') |
| 31 | +export class AnimalDisplay extends LitElement { |
| 32 | + @property({ type: String }) animal: Animal = 'dogs' |
| 33 | + |
| 34 | + // Subscribes the host to changes in `state[animal]` only. |
| 35 | + _ = new TanStackStoreSelector( |
| 36 | + this, |
| 37 | + () => store, |
| 38 | + (state) => state[this.animal], |
| 39 | + ) |
| 40 | + |
| 41 | + render() { |
| 42 | + return html`<div>${this.animal}: ${store.state[this.animal]}</div>` |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +@customElement('animal-increment') |
| 47 | +export class AnimalIncrement extends LitElement { |
| 48 | + @property({ type: String }) animal: Animal = 'dogs' |
| 49 | + |
| 50 | + render() { |
| 51 | + return html` |
| 52 | + <button @click=${() => updateState(this.animal)}> |
| 53 | + My Friend Likes ${this.animal} |
| 54 | + </button> |
| 55 | + ` |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +@customElement('tanstack-store-demo') |
| 60 | +export class TanStackStoreDemo extends LitElement { |
| 61 | + render() { |
| 62 | + return html` |
| 63 | + <div> |
| 64 | + <h1>How many of your friends like cats or dogs?</h1> |
| 65 | + <p> |
| 66 | + Press one of the buttons to add a counter of how many of your |
| 67 | + friends like cats or dogs |
| 68 | + </p> |
| 69 | + <animal-increment animal="dogs"></animal-increment> |
| 70 | + <animal-display animal="dogs"></animal-display> |
| 71 | + <animal-increment animal="cats"></animal-increment> |
| 72 | + <animal-display animal="cats"></animal-display> |
| 73 | + </div> |
| 74 | + ` |
| 75 | + } |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | +Then mount the root element in your HTML: |
| 80 | + |
| 81 | +```html |
| 82 | +<tanstack-store-demo></tanstack-store-demo> |
| 83 | +<script type="module" src="/src/index.ts"></script> |
| 84 | +``` |
0 commit comments