Anything that produces a result, like guests.length. Written inside { }.In the glossary
that the page watches: change it, and every spot that shows it updates.
import { state } from '@markless/core';export default functionProfilefunction Profile(): Element() @{@{ · Statement containerHolds instructions: setup lines, then the element to show. letnamelet name: string=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.('Jack'); <section<section> · HTML elementA section of a page, usually with its own heading.> <h2<h2> · HTML elementA second-level heading.>Hello, {name}</h2<h2> · HTML elementA second-level heading.> <button<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() => (name = 'Ada')}> Switch user </button<button> · HTML elementA button a person can press.> </section<section> · HTML elementA section of a page, usually with its own heading.>}
state('Jack') makes name a value the page watches. Nothing else changes: you still read it as name and change it with =.
An ordinary variable never updates the page
Below is a shop page. The jar beside it holds the number of bags in the cart, kept in an ordinary variable with no state(). Press Add to cart and watch both.
A pen-and-ink drawing of a desk. A sheet of paper on it is drawn as a shop page at beanshop.dev: the shop name Beanshop, a cart icon with a count badge showing 0, a bag of coffee beans sold as House blend · 250 g for $14, a pink Add to cart button, and the line "In your cart: 0 bags". Beside the sheet stands a glass jar tagged cart, one bean per bag. A thin wire runs from the button into the jar. Two more wires come out of the jar's lid, but they lie loose on the desk, their clips resting short of the page: nothing on the page is wired. Press the drawing, or Enter or Space, to add a bag: a bean drops into the jar, but the badge and the cart line still say 0. Escape empties the jar.
The jar is empty, and the page still shows 0.
The page showed the variable's first value, 0, and stops there. The jar fills up, and the page still says 0.
State updates every spot that shows it
Here is the same shop with one change: cart is made with state(). Now a wire runs from the jar to each spot that shows the count. Markless laid those wires while building the page, before anyone opened it.
Press Add to cart again.
A pen-and-ink drawing of a desk. A sheet of paper on it is drawn as a shop page at beanshop.dev: the shop name Beanshop, a cart icon with a count badge, a bag of coffee beans sold as House blend · 250 g for $14, a pink Add to cart button, and the line "In your cart" with the count in a yellow wash. Beside the sheet stands a glass jar tagged cart, one bean per bag. A wire runs from the jar's lid to a clip on the cart badge, with a branch to a clip on the cart line; a thin wire runs from the button back to the jar. Nothing else on the page is wired. Press the drawing, or Enter or Space, to add a bag: a bean drops into the jar and both wired counts are crossed out and rewritten together. Escape empties the cart.
The cart badge and the cart line now show 3.
Every spot that shows the value changes together.
Only the handler you pressed runs.
The component function never runs again. It ran once, to set up the page.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';export default function Cart() @{ let cart = state(0); <sectionclass="beanshop" style={'--n:' + cart}> <header> Beanshop <spanclass="basket"> <bhidden={cart === 0}>{cart}</b> </span> </header> <p>House blend · 250 g · $14</p> <divclass="shelf"></div> <p>In your cart: {cart}</p> <p>Total: ${cart * 14}</p> <buttondisabled={cart >= 6}onClick={() => cart++} > Add to cart </button> </section>}
To do: Press Add to cart. A bag leaves the shelf, and the badge, the count and the total change with it.
To do: Make each press add two bags: cart += 2.
To do: Try breaking it: change state(0) to a plain 0. The build stops, because the page would never show the change.
How is this different from setters and signals?
Setters, as in React's useState, run your whole component again and compare the result with what's on the page. Signals skip that: a write goes straight to the spots that read it. But they find those spots while the code runs, by recording every read, which is why you read through .value or a function call.
Markless gives you the same fine-grained updates and works out the spots at compile time. Each state() becomes a node in a graph, and each spot that reads it becomes a subscription written into the build. A write marks its node as changed and updates only the spots subscribed to it. Nothing is tracked while the page runs, so name can stay a plain let.
Numbers, text and true/false change with any assignment
Any assignment counts: adding, counting up or down, flipping true to false, or changing text. The player below skips ahead with seconds += 10 and pauses with playing = !playing.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';export default function Player() @{ let seconds = state(0); let playing = state(false); let timerId = state(0); const tick = () => seconds++; function toggle() {playing = !playing;clearInterval(timerId); if (playing) {timerId = window.setInterval(tick, 1000); } } <sectionclass="player"> <divclass={playing ? 'disc spin' : 'disc'} /> <progressvalue={seconds} max="100" /> <p> {seconds}s, {playing ? 'playing' : 'paused'} </p> <buttononClick={toggle}> Play or pause </button> <buttononClick={() => (seconds += 10)}> Skip 10s </button> </section>}
To do: Add a Back 10s button that runs seconds -= 10.
To do: Show {playing} on its own line, and press Play or pause.
An object changes field by field
Put an object in state() and change one field with a plain assignment. person.age++ updates the spots that show age. The spots that show name stay as they are.
The card below is one object with a name and an age. Press Go undercover, then Birthday: each press rewrites only its own line.
An ink drawing of a paper ID card: a photo of a smiling man, the name Lalo and the age 41. Go undercover strikes out the name, writes the other one and puts joke-shop glasses and a moustache on his face; Birthday changes the age only and leaves the name and the disguise alone.PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';import { motto } from './mottos.ts';export default function Person() @{ let person = state({ name: 'Sam', age: 8 }); function later() {person.age = (person.age + 20) % 100; } function photo() { return `/examples/ink/sam-${person.age}.svg`; } <sectionclass="agesim"> <h1>Age simulator</h1> <imgsrc={photo()} alt="" /> <h2>{person.name}</h2> <p>Age {person.age}</p> <q>{motto(person.age)}</q> <buttononClick={later}> 20 years later </button> </section>}
const mottos: Record<number, string> = { 8: 'I will be an astronaut', 28: 'It works on my machine', 48: 'I bought a standing desk', 68: 'Back in my day, we had jQuery', 88: 'Still 400 tabs open',};export function motto(age: number) { return mottos[age];}
To do: Press 20 years later a few times. Sam grows up and grows old; the name is never touched.
To do: Add a Rename button that runs person.name = 'Ada'.
To do: Add <p>{person.name} is {person.age}</p>, and press the button again.
A field inside a field works the same way, at any depth:
letpersonlet person: { name: string; address: { city: string; }; }=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.({ name: 'Jack', address: { city: 'Austin' } });<button<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() => (person.address.city = 'Denver')}>Move</button<button> · HTML elementA button a person can press.>
Replace the whole object, or change one field
All three buttons below update the page. Pick the one that says what you mean: a new hero, a copy with one change, or new values for some fields.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';export default function Hero() @{ let hero = state({ name: 'Jack', role: 'warrior', }); function reroll() {hero = { name: 'Zed', role: 'rogue' }; } function mage() {hero = { ...hero, role: 'mage' }; } function healer() { Object.assign(hero, { role: 'healer' }); } <sectionclass="classpick"> <imgsrc={`/examples/ink/state-${hero.role}.svg`}alt="" /> <p>{hero.name} the {hero.role}</p> <buttononClick={reroll}>New hero</button> <buttononClick={mage}>Copy as mage</button> <buttononClick={healer}>Make healer</button> </section>}
To do: Press Copy as mage. The name stays and the class changes.
To do: Press New hero, then Make healer. New hero replaces everything; Make healer assigns only the class.
Coming from React?
You don't have to copy an object to change it. Changing it in place updates the page too.
A field you add later shows up
A field can be missing at first. The page shows it as soon as you write it.
letpersonlet person: { name: string; nickname?: string; }=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.<{ name(property) name: string: string; nickname(property) nickname?: string | undefined?: string }>({ name: 'Jack' });<p<p> · HTML elementA paragraph.>{person.nickname ?? 'no nickname'}</p<p> · HTML elementA paragraph.><button<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() => (person.nickname = 'J')}>Nickname</button<button> · HTML elementA button a person can press.>
Destructure state, and it still updates
const { name, age } = person is ordinary destructuring, and it doesn't copy the values. age keeps reading the state, so the page shows the new age after a birthday.
letpersonlet person: { name: string; age: number; }=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.({ name: 'Jack', age: 24 });const { nameconst name: string, ageconst age: number } = person;<p<p> · HTML elementA paragraph.>{name} is {age}</p<p> · HTML elementA paragraph.><button<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() =>person.age(property) age: number++}>Birthday</button<button> · HTML elementA button a person can press.>
An array changes with the methods you know
Change an array in place with push, sort, splice and the rest of its methods, or replace it with a new one. Both update the page.
The rack below holds an array of letter tiles that spells STOP. Press reverse and it spells POTS.
tiles = ['S', 'T', 'O', 'P']
An ink drawing of letter tiles standing on a rack numbered from 0, spelling STOP, with a tile bag beside it. The buttons run array methods on tiles: push takes the next tile from the bag and stands it at the end, pop drops the last tile back in the bag, reverse turns the word round, and sort puts the letters in alphabetical order. Escape starts again.
The hand of cards below is an array too. Draw puts a card on the end with push, Discard takes the last one off with pop, and Reverse turns the hand round. The @for block draws one card for each item.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
// Runs a change as a view transition: the browser// animates from the old page to the new one.export function glide(change: () => void) { if (document.startViewTransition) { // A quick second press skips this one: fine. document .startViewTransition(change) .ready.catch(() => {}); } else { change(); }}
/* Each card turns round a point far below, 9deg from its neighbour. */.hand li { transform-origin: 50% 220%; rotate: calc( (sibling-index() - (sibling-count() + 1) / 2) * 9deg ); transition: transform 0.2s; view-transition-name: match-element; &:nth-child(1) { view-transition-class: s1; } &:nth-child(2) { view-transition-class: s2; } &:nth-child(3) { view-transition-class: s3; } &:nth-child(4) { view-transition-class: s4; } &:nth-child(5) { view-transition-class: s5; } &:nth-child(6) { view-transition-class: s6; }}.hand li:hover { transform: translateY(-1.4rem);}/* Keeps the hover while the card lifts away. */.hand li:hover::after { content: ''; position: absolute; inset: 0 0 -2rem;}/* In a view transition each card is a snapshot; the page itself stays put. */::view-transition-old(root) { display: none; }::view-transition-new(root) { animation: none; }/* Cards keep their old overlap until they meet in the middle, then take their new one. */::view-transition { animation: restack 0.45s;}@keyframes restack { 0%, 29% { --restack: 0; } 30%, 100% { --restack: 1; }}::view-transition-group(*.s1) { --z: 1; }::view-transition-group(*.s2) { --z: 2; }::view-transition-group(*.s3) { --z: 3; }::view-transition-group(*.s4) { --z: 4; }::view-transition-group(*.s5) { --z: 5; }::view-transition-group(*.s6) { --z: 6; }::view-transition-group(*) { animation-duration: 0.45s; z-index: calc(var(--z, 0) * var(--restack, 1));}::view-transition-new(*):only-child { animation: deal 0.45s ease-out;}::view-transition-old(*):only-child { animation: discard 0.35s ease-in forwards;}@keyframes deal { 0%, 30% { opacity: 0; translate: 1rem -6rem; } 45% { opacity: 1; }}@keyframes discard { to { opacity: 0; translate: 0 3rem; }}@media (prefers-reduced-motion: reduce) { .hand li, ::view-transition, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { transition: none; animation: none; }}
Resize code and preview
3 cards
7♠
Q♥
3♣
Try this
To do: Press Draw. A fourth card lands at the end of your hand.
To do: Add a Sort button that runs glide(() => hand.sort()).
To do: Discard from the front instead: change hand.pop() to hand.shift().
Change one item in an array
Tonight's seats arrive as an array of objects in tonight.ts, each with an id, whether it is sold, and whether you have picked it. state(tonight) makes that array the component's state. The @for@for · ListShows its block once per item. It needs a key. block draws one seat for each item. A seat's own button changes only that item: seat.picked = !seat.picked. A loop that clears your seats works too.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';import { tonight } from './tonight.ts';export default function Seats() @{ let seats = state(tonight); function count() { return seats.filter((s) => s.picked).length; } function summary() { const n = count(); const word = n === 1 ? 'seat' : 'seats'; return `${n} ${word} · $${n * 12}`; } function clear() { for (const s of seats) s.picked = false; } <sectionclass="seats"> <pclass="screen">Screen</p> <div>@for (const seat of seats; key seat.id) { <buttondisabled={seat.sold} aria-pressed={seat.picked}onClick={() => (seat.picked = !seat.picked)} > {seat.id} </button> } </div> <ulclass="key"> <li>Free</li> <liclass="yours">Yours</li> <liclass="sold">Sold</li> </ul> <p>{summary()}</p> <buttondisabled={count() === 0}onClick={clear} > Clear my seats </button> </section>}
To do: Pick A2 and B4. Only those two seats and the price line change.
To do: Pick B1 for a friend with a button that runs seats[4].picked = true.
To do: Let Clear my seats free the sold seats too: in its loop, add s.sold = false.
Each seat is written once, inside @for. Lists covers @for and its key in full.
A Map updates on set and delete
A Map is JavaScript's built-in lookup table: each key has one value. Put one in state(), and everything that reads it updates when you set, delete or clear.
The vending machine below keeps its stock in one: each slot code holds a snack and how many are left. Buying one sets a lower count, and buying the last one deletes the slot. The snack drops into the tray; push the flap to take it.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';import { SLOTS, START } from './machine.ts';import { drop, take } from './drop.ts';export default function Vending() @{ let stock = state(new Map(START)); let screen = state('Pick a snack'); const push = () => (screen = take()); function buy(slot: string) {drop(slot); const item = stock.get(slot); if (!item) {screen = slot + ' is empty'; } else if (item.left === 1) {screen = 'Last one! ' + item.snack; stock.delete(slot); } else {screen = 'Enjoy! ' + item.snack; const left = item.left - 1; stock.set(slot, { ...item, left }); } } <sectionclass="vink"> <pclass="screen">{screen}</p>@for (const slot of SLOTS; key slot) { <button aria-describedby={slot}onClick={() => buy(slot)} > {slot} </button> }@for (const [at, item] of stock; key at) { <iid={at} data-snack={item.snack} data-left={item.left} > {item.snack}, {item.left} left </i> } <divclass="tray" /> <buttonclass="flap" onClick={push}> PUSH </button> <p>Slots stocked: {stock.size}</p> </section>}
To do: Buy the last cookie in A2. The slot is deleted, and the stocked count drops to 5.
To do: Restock A2: add a button that runs stock.set('A2', { snack: 'cookie', left: 3 }).
To do: The owner empties it for the night: add a button that runs stock.clear().
A Set updates on add and delete
A Set is JavaScript's built-in collection with no repeats: add a value twice and it keeps one. Put one in state(), and everything that reads it updates when you add, delete or clear.
The gauntlet below holds its gems in one. Drag a gem on and it is added; drag a second gem of the same colour and nothing changes, because the Set already has it. With all six in, Snap runs clear().
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { element, state } from '@markless/core';import * as drag from './drag.ts';import * as gems from './gems.ts';export default function Gauntlet() @{ let glove = state(new Set<string>()); let pile = state(gems.PILE.slice()); const fist = element<HTMLDivElement>(); const seated = element<HTMLElement[]>(); const heap = element<HTMLDivElement>(); function place({ id, colour }: gems.Gem) { if (glove.has(colour)) return gems.bounce(); glove.add(colour);pile = pile.filter((g) => g.id !== id); gems.fly(seated); } function snap() { glove.clear();pile = gems.PILE.slice(); } <sectionclass="gauntlet"> <divel={fist} class="fist"onDragOver={drag.over}onDragLeave={drag.leave}onDrop={(e) => drag.land(e, place)} >@for (const colour of glove; key colour) { <iel={seated} class={colour} /> } </div> <p>{glove.size} of 6</p> <divel={heap} class="pile">@for (const gem of pile; key gem.id) { <buttonclass={gem.colour} aria-label={gem.colour}draggable="true"onDragStart={(e) => drag.lift(e, gem)}onClick={(e) => place(drag.tap(e, gem))} /> } </div> <buttonclass="snap" disabled={glove.size < 6}onClick={() => gems.snap(fist, seated, heap, snap)} >Snap</button> </section>}
import { grip } from './drag.ts';export interface Gem { id: number; colour: string;}// Nine gems, three colours twice.export const PILE: Gem[] = [ 'red', 'blue', 'orange', 'green', 'red', 'purple', 'yellow', 'blue', 'green',].map((colour, id) => ({ id, colour }));const still = '(prefers-reduced-motion:reduce)';const calm = () => matchMedia(still).matches;const move = (x: number, y: number, more = '') => `translate(${x}px, ${y}px) ${more}`;// From `el`'s centre to the centre of `at`.function offset(el: HTMLElement, at: DOMRect) { const { x, y, width, height } = el.getBoundingClientRect(); return { dx: at.x - x + (at.width - width) / 2, dy: at.y - y + (at.height - height) / 2, };}// A Set adds at the end: the new gem is last.export function fly(seated: HTMLElement[] = []) { const gem = seated.at(-1); const at = grip.start; if (!gem || !at || calm()) return; const { dx, dy } = offset(gem, at); const k = at.width / gem.offsetWidth; const half = `scale(${(k + 1) / 2})`; const rise = dy / 2 - 40; const flight = gem.animate( [ { transform: move(dx, dy, `scale(${k})`) }, { transform: move(dx / 2, rise, half), offset: 0.45, }, { transform: 'scale(1.12)', offset: 0.82 }, { transform: 'none' }, ], { duration: 420, easing: 'ease-out' }, ); flight.onfinish = () => glow(gem);}function glow(gem: HTMLElement) { const colour = getComputedStyle(gem) .getPropertyValue('--glow'); const flare = `drop-shadow(0 0 1rem ${colour})`; gem.animate([{ filter: flare }, {}], { duration: 700, easing: 'ease-out', });}export function bounce() { const { from, start } = grip; if (!from || !start || calm()) return; const { dx, dy } = offset(from, start); from.animate( [ { transform: move(dx, dy) }, { transform: move(dx / 2, dy / 2 - 28), offset: 0.55, }, { transform: move(0, 3, 'rotate(6deg)'), offset: 0.85, }, { transform: 'none' }, ], { duration: 480, easing: 'ease-out' }, );}// Seated gems burst where they sit, then the// pile refills with new ones.export async function vanish( seated: HTMLElement[] = [], heap: HTMLElement | undefined, change: () => void,) { if (!calm()) { await Promise.all(seated.map(dust)); } change(); heap?.classList.add('refill');}function dust(gem: HTMLElement, i: number) { const colour = getComputedStyle(gem) .getPropertyValue('--glow'); const flare = `drop-shadow(0 0 9px ${colour})`; return gem.animate( [ {}, { transform: 'scale(1.35)', filter: `brightness(1.8) ${flare}`, offset: 0.3, }, { transform: 'translateY(-26px) scale(.3)', filter: 'blur(4px)', opacity: 0, }, ], { duration: 550, delay: i * 60, easing: 'ease-in', fill: 'forwards', }, ).finished;}// Trial: the glove snaps first. To drop it, call// vanish without `fist` and delete to the end.const wait = (ms: number) => new Promise((done) => setTimeout(done, ms));const poses = [ ['snap1', 140], ['snap2', 200],] as const;export async function snap( fist: HTMLElement | undefined, seated: HTMLElement[] = [], heap: HTMLElement | undefined, change: () => void,) { if (fist && !calm()) { for (const [pose, ms] of poses) { fist.classList.add(pose); await wait(ms); fist.classList.remove(pose); } } await vanish(seated, heap, change);}
import type { Gem } from './gems.ts';// What is in hand; gems.ts reads it for motion.export const grip: { gem?: Gem; from?: HTMLElement; start?: DOMRect;} = {};function pick(e: Event, gem: Gem) { const from = e.currentTarget; if (!(from instanceof HTMLElement)) return; grip.gem = gem; grip.from = from; grip.start = from.getBoundingClientRect();}export function lift(e: DragEvent, gem: Gem) { pick(e, gem); e.dataTransfer?.setData('text', '');}export function tap(e: Event, gem: Gem) { pick(e, gem); return gem;}export function over(e: DragEvent) { e.preventDefault(); mark(e, true);}export function leave(e: DragEvent) { mark(e, false);}function mark(e: Event, on: boolean) { const fist = e.currentTarget; if (fist instanceof HTMLElement) { fist.classList.toggle('over', on); }}// The flight starts where the gem was let go.export function land( e: DragEvent, place: (gem: Gem) => void,) { e.preventDefault(); leave(e); const { gem, start } = grip; if (!gem || !start) return; const { width: w, height: h } = start; const x = e.clientX - w / 2; const y = e.clientY - h / 2; grip.start = new DOMRect(x, y, w, h); place(gem);}
To do: Drag both reds onto the glove. Only one goes in: 1 of 6.
To do: Add a button that pops one out: glove.delete('red').
A Date updates through its own set methods
Call a set method on the date, or assign a new date. Both update the page.
letbirthdaylet birthday: Date=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.(newDatevar Date: DateConstructor new (value: number | string | Date) => Date (+3 overloads)('2026-11-05T00:00'));<p<p> · HTML elementA paragraph.>{birthday.toDateString(method) Date.toDateString(): stringReturns a date as a string value.()}</p<p> · HTML elementA paragraph.><button<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() => birthday.setDate(method) Date.setDate(date: number): numberSets the numeric day-of-the-month value of the Date object using local time.(birthday.getDate(method) Date.getDate(): numberGets the day-of-the-month, using local time.() + 1)}> Next day</button<button> · HTML elementA button a person can press.>
Can I make the date first and pass it in?
Yes. state() takes any value, so this works the same:
conststartconst start: Date = newDatevar Date: DateConstructor new (value: number | string | Date) => Date (+3 overloads)('2026-11-05T00:00');letbirthdaylet birthday: any=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.(start);
start only gives the state its first value. After that, change the date through birthday. The build refuses a handler that changes start instead, such as start.setDate(6), because start is not state and the change would never reach the page.
The same goes for an array or an object you make first and pass to state().
A write can come later
A handler can change state after an await or inside a timer. The page shows each change when it happens.
Casting below writes three times: once at the press, once when the fish bites two seconds later, and once more for the count.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';function wait(ms: number) { return new Promise((ok) => setTimeout(ok, ms));}export default function Fishing() @{ let line = state('in'); let caught = state(0); async function cast() {line = 'waiting'; await wait(2000);line = 'bite';caught++; } <sectionclass={'pond ' + line}> <p> Caught: <b>{caught}</b> </p> <div> <spanclass="rod"></span> <spanclass="hook"> <spanclass="float"></span> <spanclass="fish"></span> </span> </div> <buttondisabled={line === 'waiting'}onClick={cast} > Cast </button> </section>}
To do: Cast twice. Each time the float bobs, then a fish bites.
To do: A slow day: change 2000 to 5000.
A function can change state you pass it
Pass person to a function, and the function's change reaches the page:
functionbirthdayfunction birthday(p: { age: number; }): void(p(parameter) p: { age: number; }: { age(property) age: number: number }) {p.age(property) age: number++;}<button<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() =>birthdayfunction birthday(p: { age: number; }): void(person)}>Birthday</button<button> · HTML elementA button a person can press.>
Give state a type
TypeScript takes the type from the starting value. When the starting value is narrower than what the state will hold, pass the type: state<T>(initial: T): T.
typeSorttype Sort = "newest" | "oldest" = 'newest' | 'oldest';letsortlet sort: Sort=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.<Sorttype Sort = "newest" | "oldest">('newest');lettodoslet todos: Todo[]=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.<Todoimport Todo[]>([]);
Mistakes the build catches for you
Take a shot. The ball carries a mistake, and the keeper is the build: he saves every one and hands it back fixed.
An ink drawing of a football goal with a net, a goalkeeper in gloves, and a ball on the penalty spot. A paper tag tied to the ball carries one mistake from this section as code, such as let cart = 0. Drag from the ball to aim anywhere in the goal, click a spot in the goal, press the ball, or use the arrow keys to aim and Enter to shoot. The keeper dives wherever it goes and saves it every time; the ball comes back, the mistake is struck through in red, and the fix is written under it, such as let cart = state(0). Each shot carries the next mistake. Escape starts again.
Markless checks every state() while it builds. Each mistake below stops the build with a message that says what to change, so it never reaches a visitor:
state() above the component. Up there, one value would be shared by every visitor. Move it into the component, or use shared when sharing is the point.
state() inside a handler or an @for@for · ListShows its block once per item. It needs a key.. Write it next to your other variables in the component.
A plain let changed in a handler. The page would never show the change, so wrap it in state().
A function kept in state. Keep the data in state, and the function outside it.
A field changed on an object you read out of a Map or a Set. Put a new object back with votes.set(...) instead.
An instance of your own class kept in state, such as state(new Counter()). State is sent from the server to the browser as data, and a class's methods can't make that trip. Keep a plain object in state instead.
state() works in .tsrx files only.
Events shows the handlers that make these changes.