Class StateContainer<Value, RefVal>Abstract

Convenient container class to hold a reference object and value to allow for easy (but manual) state management. Just implement the update function by taking advantage of the ref object.

Example

Tic-tac-toe example

let currentPlayer: "x" | "o" = "x"

class SquareState extends StateContainer<"" | "x" | "o", HTMLDivElement | null> {
constructor() {
super("")
}

public updateDOM(squareRef: Ref<HTMLDivElement>) {
squareRef.current.innerText = this.value
}
}

...
const square = new SquareState()

createElement(
"div",
{
class: "col-4",
onClick: () => {
// Check if square isn't already clicked
if (square.value === "") {
// Setter sets the value and then invokes `updateDOM`
square.value = currentPlayer
// Alternatively, `square.update(currentPlayer)` may be easier to understand
}

// Change current player
currentPlayer = currentPlayer === "x" ? "o" : "x"
},
},
createElement(
"div",
// We can attach the ref and value to some element
{class: "tictactoe-square", ref: square.ref},
square.value,
),
)
...

Remark

this pattern will get very messy if things are too complicated.

Type Parameters

  • Value
  • RefVal extends Node | null = Node | null

Constructors

Properties

Accessors

Methods

Constructors

  • Really funny constructor here, but it's just to allow omission of the reference parameter in the case that it's marked as null (normally this would be a function overload).

    In other words, if the ref can be null, you can omit the second argument and a ref will be created for you with null as the default value.

    Type Parameters

    • Value
    • RefVal extends null | Node = null | Node

    Parameters

    Returns StateContainer<Value, RefVal>

Properties

#value: Value

State value, not actually reactive

ref: Ref<RefVal>

Ref object

Accessors

Methods

Generated using TypeDoc