Skip to main content
Version: Current

foundation-layout.layoutcomponentwithstate

Home > @genesislcap/foundation-layout > LayoutComponentWithState

LayoutComponentWithState interface

Interface to implement on an item which is a component of the layout and you wish to serialise state with. This is saved separately for each instance of the component, which allows you to restore multiple instances of the same component with different state.

Signature:

export interface LayoutComponentWithState<T> 

Remarks

When the layout is saved either via the autosave functionality or manually calling FoundationLayout.getLayout(), all contained components will be requested to provide state if they wish.

Any state which is provided will be saved as part of the layout config and will be passed back to the component when the layout is loaded with FoundationLayout.loadLayout() (or via autoloading). The state will be applied to the component via applyState, this may be before or after the component has been placed on the DOM, so you'll need to handle either scenario. The state is null when the instance is first created.

See the written documentation for some error scenarios to consider about when implementing this interface.

Example 1

type ComponentState = {
foo: string;
}
\@customElement({ name: 'my-component' })
export class MyComponent extends FASTElement implements LayoutComponentWithState<ComponentState> {
\@observable foo: string;
private fooCache: ComponentState | null;

getCurrentState(): ComponentState {
if (!this.foo) return null;
return {
foo: this.foo;
}
}

applyState(state: ComponentState | null) {
this.fooCache = state;
}

connectedCallback() {
// do other required setup
if (this.fooCache) {
this.foo = this.fooCache.foo;
}
}
}

Example 2

If you are using the autosave functionality you should inform the layout system when you update the state of a component, otherwise the state will only be updated when the user performs an action such as resizing an item. Use the LayoutReceiveEvents autosave event.

// Same component as above
export class MyComponent extends FASTElement implements LayoutComponentWithState<ComponentState> {
// can use xChanged pattern as `foo` was declared observable
fooChanged() {
this.$emit(LayoutReceiveEvents.autosave);
}
}

Methods

MethodDescription
applyState(state)Handle any state that has been saved previously for this instance of this component. It is not deterministic to know whether this is called before the component is appended to the DOM.
getCurrentState()Provide the state you wish to save. It is recommended if the component which implements this interface has not fully initialised at the point this is called that you return null as the state, following the pattern of null being set as the initial state.