Skip to content

Widget Client Documentation

Alexei Darmin edited this page Feb 26, 2022 · 4 revisions

Quick start

import { WidgetClient } from "@statflo/widget-sdk";

const client = new WidgetClient({ 
  id: name,
  window,
  createWidgetState: (id) => ({ id })
});

Initialization mandatory properties:

  • id the unique string identifier of this widget.
  • window the window object that will be used to .postMessage() to the container client.
    • For server-side rendered JS, a synthetic window can be used to build successfully such as the domino NPM package.
  • createWidgetState is a function that takes the widget id and returns an object with all the initial properties of the widget state.

Methods

setState()

setState(property, value) : Updates the state of the widget by setting the property to equal the value. Syncs local widget state with remote container state, triggering all downstream callbacks for the container's state subscribers as well.

post()

post(eventName, value) : Posts an event to the container with eventName and value

postForward()

postForward(eventName, value, recipientId) : Method for posting an event to another widget where id = recipientId. The container, upon receiving this event, will trigger a post to the designated recipientId and event with the name eventName and payload value.

.on()

.on(eventName, callback) : A method to subscribe a callback to the designated event name. Note that this function can also subscribe to event methods such as containerMethods.setState.

Managing state

  • A widget's state can be modified by invoking the client.setState().
  • One property can be changed at a time
    • For example in order to store "myValue" into the property "myProp" one would execute client.setState("myProp", "myValue").
  • Widget state updates propagate to the container, and subscribers to the container's state as well. See container receiving state updates for more info.

Sending state updates

client.setState("header", "my cool widget");

Receiving state updates

import { ContainerMethods } from "@statflo/widget-sdk/dist/shared";

client.on(ContainerMethods.setState, (e) => {
  const { property, value } = e.payload;
  ... 
});

Managing events

  • Widgets can send events to the container that don't result in stateful updates.
  • This can be accomplished via the client.post() method.

Sending events

client.post("myEventName", "myEventPayload")

This will trigger any functions within the container client that are subscribed to "myEventName"

Receiving events

client.on("containerEventName", (e) => { ... })