stew/* Packages / 14.4
💾 stew/storage
The stew/storage package provides a reactive and idiomatic interface for the browser's storage APIs (LocalStorage and SessionStorage).
Local vs Session
storage.Local
Uses
window.localStorage. Data persists even after the tab or browser is closed.storage.Session
Uses
window.sessionStorage. Data is kept only for the duration of the current tab.Available Methods (Local & Session)
| Method | Role |
|---|---|
| Get(key string) string | Retrieves a value. Returns an empty string if missing. |
| Set(key, val string) | Saves a value. |
| Remove(key string) | Deletes a key. |
| Clear() | Clears all data from this storage area. |
| Bind(signal *state.Signal[string], key string) | Two-way reactive binding (see below). |
Reactivity: Bind(signal, key)
This is the most powerful feature of the package. It allows you to transparently synchronize a Go variable with a storage key.
- Upon loading, the variable is initialized with the value from storage (if it exists).
- If you modify the variable in Go, the storage is automatically updated.
- If you bind the variable to an HTML input, the value will persist between page refreshes.
<goscript client>
import "stew/storage"
import "stew/state"
userName := state.New("Visitor")
// Instant binding with a LocalStorage key
storage.Local.Bind(userName, "cached_name")
</goscript>
<input type="text" bind:value={{userName}} />
<p>Persisted Name: {{userName}}</p>