state() holds a class instance
The message
MARKLESS_STATE_CLASS_INSTANCE: state "<name>" holds <held>. Class instances in state are not supported yet: the server render cannot write one into the page, and a method that changes `this` records no change, so the page would not update.
state() crosses from the server to the browser as data. A class instance is data plus methods, and the methods do not cross: the browser would get a plain object, and a write made inside a method is invisible to Markless.
Keep the fields as plain data in state and turn each method into a function beside it that takes the data: `function update(<name>, ...) { ... }`, called as `update(<name>, ...)`. Markless tracks what that function changes.
https://markless.dev/errors/MARKLESS_STATE_CLASS_INSTANCEWords in angle brackets change from case to case.
Why
State reaches the browser as data. A class instance is data plus methods, and the methods do not come along, so the server render could not write it into the page and a method that changes this would leave the page stale. Markless refuses new X() in a state() initializer, alone or as array elements, unless X is a built-in it can send, such as Date, Map or Set. What the build does not catch yet: an instance returned from a function or a static factory (state(makeCart()), Cart.create()), one nested in an array of arrays, inside an object in an array, behind a condition (ok ? new Cart() : null), as a Map value, under a computed key, made with Object.create, or assigned or pushed later in a handler (cart = new Cart(), carts.push(new Cart())). Those still build, then fail at server render or leave the page stale.
Fix
Keep the fields as plain data in state and move each method into a function beside it that takes the data. Markless tracks what that function changes. Or keep plain data in state and build the instance inside the handler that needs it.
Before
import { state } from '@markless/core';class Cart { bags = 0; add(n: number) { this.bags += n; }}export function Shop() @{ let cart = state(new Cart()); <button onClick={() => cart.add(1)}>{cart.bags}</button>}After
function add(cart: { bags: number }, n: number) { cart.bags += n;}export function Shop() @{ let cart = state({ bags: 0 }); <button onClick={() => add(cart, 1)}>{cart.bags}</button>}Related
Where Markless raises it
Button sounds are from Josh Comeau's Button Sounds library.