State & Storage
ZhinNX punya state layer kecil untuk data app yang umum. Kamu bisa membuat state bernama, membaca value nested, mengubah value, update dengan callback, dan subscribe ke perubahan.
import {
state,
get,
set,
update,
subscribe,
save,
load
} from 'zhinnx'
state('counter', { count: load('count', 0) })
subscribe('counter', value => {
save('count', value.count)
})
set('counter.count', 1)
update('counter.count', value => value + 1)
console.log(get('counter.count'))Kapan memakai state
Pakai state untuk data yang perlu dibaca oleh beberapa page atau action. Contohnya user aktif, lagu aktif, preferensi tema, draft form, tab aktif, dan cache hasil API.
Helper localStorage
| Helper | Fungsi |
|---|---|
save(key, value) | Menyimpan data JSON-serializable. |
load(key, fallback) | Mengambil data atau mengembalikan fallback. |
remove(key) | Menghapus data tersimpan. |
Kesalahan umum
Jangan masukkan semua data ke state global. Kalau value hanya dipakai di satu render function, simpan sebagai data lokal.
Update state yang aman untuk FastLoad
Di halaman FastLoad, perubahan UI kecil sebaiknya tidak memicu render ulang seluruh route. Untuk counter cart, tombol liked, badge, dan toggle kecil, update state dengan { render: false }, lalu patch area UI yang berubah.
update('shop.cart', cart => {
const next = Array.isArray(cart) ? [...cart] : []
next.push({ id: 'product-1', qty: 1 })
save('cart', next)
return next
}, { render: false })
patch('.cart-count', get('shop.cart', []).length)Jika debug mode aktif, ZhinNX memberi warning ketika update state menyebabkan full render saat FastLoad aktif.