Skip to main content

Nesting

Nesting states is perfectly doable and encouraged. Let's say you are building a game where you have a hero, and this hero have attributes:

import { superstate } from '@superstate/core'

const hp = superstate(100)
const hero = superstate({ attributes: { hp } })

hero.now().attributes.hp.set((prev) => prev - 50)

To make you life easier, you can create helper functions:

const attributes = { hp: attribute(100) }

function attribute(initial: number) {
const state = superstate(initial)

function decrease(amount: number) {
state.set((prev) => prev - amount)
},

function increase(amount: number) {
state.set((prev) => prev + amount)
}

function now() {
return state.now()
}

return { decrease, increase, now }
}

const hero = {
state: superstate({ attributes }),

getAttribute(key: keyof typeof attributes) {
return hero.state.now().attributes[key]
}

heal(amount: number) {
hero.getAttribute('hp').increase(amount)
},

takeDamage(amount: number) {
hero.getAttribute('hp').decrease(amount)
}
}

hero.takeDamage(50)
hero.heal(25)

console.log(hero.get('hp')) // 75