// src/models/demo/types/index.d.ts
declare interface IDemoModel extends IDemoModelOptions, IKosDataModel {
id: string;
lastUpdate: number;
computedName: string;
}
Add new values to model interface
// src/models/demo/types/index.d.ts
declare interface IDemoModel extends IDemoModelOptions, IKosDataModel {
id: string;
lastUpdate: number;
computedName: string;
}
add new parameters to the implementation. Note that computedName
is impelmented as a
getter rather than a declard property
// src/models/demo/demo-model.ts
import { kosModel, kosTopicHandler } from "@coca-cola/kos-ui-core";
import type { ApiCallback } from "@coca-cola/kos-ui-core";
import { DemoFactory } from "./demo-factory";
import { getDemo } from "./services/demo-services";
import log from "loglevel";
import { kosAction } from "@coca-cola/kos-ui-components";
@kosModel<IDemoModel, IDemoModelOptions>(DemoFactory.type)
export class DemoModel implements IDemoModel {
id: string;
name: string;
lastUpdate: number;
constructor(modelId: string, options: IDemoModelOptions) {
// assign the id from the passed in model id
this.id = modelId;
this.name = options.name;
this.lastUpdate = 0;
}
// getters will be computed whenever name or lastUpdate changes
get computedName() {
return `${this.name} - ${this.lastUpdate}`;
}
async init(): Promise<void> {
log.info("initialized model");
}
/**
* The load lifecycle method provides an opportunity to hydrate the model with data fetched
* from the backend.
*
*/
async load(): Promise<void> {
try {
log.info("loading demo model");
const response = await getDemo(this.id);
log.debug(`received response ${response}`);
kosAction(() => {
const newName = response?.data.name;
if (newName) {
this.name = newName;
}
});
} catch (e) {
log.error(e);
throw e;
}
}
}
import { kosComponent, useKosModel } from "@coca-cola/kos-ui-components";
import { DemoFactory } from "./models/demo/demo-factory";
export const DemoComponent = () => {
const { model, ready } = useKosModel<IDemoModel, IDemoModelOptions>({
modelId: "demo1",
factory: DemoFactory,
options: { name: "demo-name" },
});
const isReady = ready && model;
return isReady ? (
<div>Computed Model Name: {model.computedName}</div>
) : (
<div>LOADING</div>
);
};
export const Demo = kosComponent(DemoComponent);