Computed values
import { computed, state } from '@markless/core';
export default function Bill() @{
let bill = state(120);
let friends = state(4);
const share = computed(() => bill / friends);
<section>
<p>{friends} of you, {share} each</p>
{/* friends and share both update on screen */}
<button onClick={() => friends--}>
Someone forgot their wallet
</button>
</section>
}You never have to update share. Whenever bill or friends changes, computed() calculates it again for you.
Tilt the board
The bubble is calculated from the tilt, so it is always right. Try pushing it to the middle.
A computed value keeps itself up to date
Everything on the page that shows a computed value changes with it.
0 kg against 6 kg of cat
- To do: Press 2 kg four times. Mochi goes up.
- To do: Add a 5 kg button: copy the 2 kg button and change both 2s to 5.
- To do: On line 6, change
sum + kgtosum + kg * 2. Every weight now counts double.
Make new computed values from the ones you have
A computed value can be used to calculate another one, and that one stays up to date too.
Heat: 0°
Marshmallow: raw- To do: Press Add a log until the marshmallow catches fire.
- To do: On line 8, change
750to950. It stays golden for one more log.
Store what happened, calculate the rest
Each swing is stored. The best score isn't: it is calculated from the swings, so there is no second number to keep in step.
Swings: 0
- To do: Hold the mallet and let go, three times. The flag stays at your best.
- To do: Show the best in words too: on line 28, add
, best {best}after the count.
Two more things a computed value can be
A list. The songs that match a search:
const shown = computed(() =>
songs.filter((song) => song.title.includes(query)),
);Lists shows each one on the page.
An answer you wait for. Today's weather, fetched from a server:
type Weather = { city: string; degrees: number };
const weather = computed(async () => {
const answer = await fetch('/api/weather');
const today: Weather = await answer.json();
return today;
});Async values shows what the page shows while it waits.
How is this different from dependency arrays and effects?
Many tools ask you to list a calculated value's inputs in a dependency array, and to run side work in an effect hook. Markless finds the inputs before your app runs, and side work stays in your function that made the change.