Vanilla Shared State Example
Vanilla JS Example
This example demonstrates how to synchronize standard HTML form inputs without a framework.
<script>
// 1. Create the agent instance ONCE.
const agentKey = "YOUR_AGENT_KEY";
const agent = window.eucera?.agent(agentKey);
const stateDescription = "This state contains fields required to collect and validate a recipient's delivery information, including full name, street, city, and postal code.";
// 2. Choose a stable key for this piece of state.
const stateKey = "shipping_address";
// 3. Create helper functions to read from and write to the DOM.
const readUI = () => ({
fullName: document.getElementById("fullName")?.value || "",
street: document.getElementById("street")?.value || "",
city: document.getElementById("city")?.value || "",
postal: document.getElementById("postal")?.value || "",
});
const writeUI = (next) => {
if (!next || typeof next !== "object") return;
Object.entries(next).forEach(([k, v]) => {
const el = document.getElementById(k);
if (el) el.value = v ?? "";
});
};
// 4. Agent -> UI: This handler listens for agent-driven updates and writes them to the DOM.
const handleStateChange = (key, nextState) => {
if (key === stateKey) {
writeUI(nextState);
}
};
// 5. On page load, perform the initial sync.
agent?.shareState(stateKey, readUI(), handleStateChange, stateDescription);
// 6. UI -> Agent: Add event listeners to send updates to the agent on user input.
["fullName", "street", "city", "postal"].forEach((id) => {
const el = document.getElementById(id);
if (!el) return;
el.addEventListener("input", () => agent?.shareState(stateKey, readUI()));
});
// 7. Use `beforeunload` to clean up the state.
window.addEventListener("beforeunload", () => agent?.clearState(stateKey));
</script>
Updated 8 days ago