Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.sure-developer.com/llms.txt

Use this file to discover all available pages before exploring further.

Track

The track module gives you a compact reactive state primitive inspired by signal-style APIs. A state returns a getter and setter. Effects subscribe to one or more getters and run when a subscribed state changes.
local track = sure.getModule('track')

State and effect

local amount, setAmount = track.state('amount', 1)

track.effect(function()
  print(('Amount changed to %s'):format(amount()))
end, { amount })

setAmount(2)
Effects are dependency based. Updating a different state will not trigger an effect unless that state’s getter is included in the dependency list.

Tables and functional updates

When the initial value, returned value, or next value is a table, sure_lib deep-clones it at the state boundary. This prevents accidental mutation of stored state through an old table reference.
local profile, setProfile = track.state('profile', {
  name = 'Sure',
  level = 1
})

local current = profile()
current.level = 99

setProfile({
  name = 'Sure',
  level = 2
})

print(profile().level) -- 2
Setters also accept a function. The function receives a copied current value and returns the next value.
local notices, setNotices = track.state('notices', {})

setNotices(function(items)
  items[#items + 1] = {
    id = 'n-1',
    message = 'Saved'
  }

  return items
end)

API

state(stateName, initialValue)
function
required
Creates a reactive state. stateName is used internally to connect dependencies to effects.
getter
function
Call the getter with no arguments to read the current value: amount().
setter
function
Call the setter with a new value or a function (currentValue) -> nextValue to update state and notify dependent effects.
effect(callback, dependencies)
function
required
Registers a callback that runs when any getter in dependencies changes.
Use track for local derived behavior inside one resource. It is not a network replication layer.