Skip to content
Source
Sign inSign up
TanStack/store
Open History to see the last commit

quick-start.md

109 lines2.5 KB

1---
2title: Quick Start
3id: quick-start
4---
5​
6The basic Lit app example to get started with TanStack `lit-store`.
7​
8You can use `TanStackStoreSelector` in two ways:
9​
10- Trigger rerenders when a selected slice changes
11- Access the selected value directly through `.value`
12​
13```ts
14import { LitElement, html } from 'lit'
15import { customElement, property } from 'lit/decorators.js'
16import { TanStackStoreSelector, createStore } from '@tanstack/lit-store'
17​
18// You can instantiate a Store outside of Lit components too!
19export const store = createStore({
20 dogs: 0,
21 cats: 0,
22})
23​
24type Animal = 'dogs' | 'cats'
25​
26const updateState = (animal: Animal) => {
27 store.setState((state) => ({
28 ...state,
29 [animal]: state[animal] + 1,
30 }))
32​
33@customElement('animal-display')
34export class AnimalDisplay extends LitElement {
35 @property({ type: String }) animal: Animal = 'dogs'
36​
37 // Subscribes only to `state[animal]`
38 counter = new TanStackStoreSelector(
39 this,
40 () => store,
41 (state) => state[this.animal],
42 )
43​
44 render() {
45 return html`
46 <div>
47 <p>
48 Using selector.value:
49 ${this.counter.value}
50 </p>
51​
52 <p>
53 Reading directly from store.state:
54 ${store.state[this.animal]}
55 </p>
56 </div>
57 `
58 }
60​
61@customElement('animal-increment')
62export class AnimalIncrement extends LitElement {
63 @property({ type: String }) animal: Animal = 'dogs'
64​
65 render() {
66 return html`
67 <button @click=${() => updateState(this.animal)}>
68 My Friend Likes ${this.animal}
69 </button>
70 `
71 }
73​
74@customElement('tanstack-store-demo')
75export class TanStackStoreDemo extends LitElement {
76 render() {
77 return html`
78 <div>
79 <h1>How many of your friends like cats or dogs?</h1>
80​
81 <p>
82 Press one of the buttons to increment how many of your friends
83 like cats or dogs.
84 </p>
85​
86 <animal-increment animal="dogs"></animal-increment>
87 <animal-display animal="dogs"></animal-display>
88​
89 <animal-increment animal="cats"></animal-increment>
90 <animal-display animal="cats"></animal-display>
91 </div>
92 `
93 }
95```
96​
97`selector.value` returns the latest selected value and only updates when
98that specific selection changes.
99​
100Reading from `store.state` accesses the full store state directly. The
101component still rerenders because the selector subscription is active,
102but the rendered value itself comes from the store.
103​
104Then mount the root element in your HTML:
105​
106```html
107<tanstack-store-demo></tanstack-store-demo>
108<script type="module" src="/src/index.ts"></script>
109```