Typescript / React: RefValue

Date: 2022-08-25
export interface IRefValue<T> {
    setValue: (value: T | undefined) => any;
    getValue: () => T | undefined;
}

export function RefValue<T>(initVal?: T): IRefValue<T> {
    let internalValue = initVal;
    const setValue = (value: T | undefined) => { internalValue = value; };
    const getValue = () => internalValue;
    return {
        getValue,
        setValue
    };
}
// Description: 
// For the situations where a local variable / up-value does not work
// Below an example how to use:

const labelCountRef = RefValue<number>(1);
const printerIdRef = RefValue<number>(0);
const printerChanged = (x?: number) => printerIdRef.setValue(x);

const ignoreWarningsAndPrintAgain = await appDomain.IRequestNotify.notify({
    showConfirmButton: true,
    showCancelButton: true,
    html: <div>
        <PrinterSelector printerChanged={printerChanged} />
        <NumbericInput length={4} value={String(labelCountRef.getValue())} onSetValue={(v: string) => labelCountRef.setValue(parseInt(v) || 0)} />
    </div>,
    cancelButtonText: translate("general.cancel"),
    confirmButtonText: translate("general.continue")
});

if (!ignoreWarningsAndPrintAgain.isConfirmed) {
    return { cancelled: true };
}
return {
    printerId: printerIdRef.getValue(),
    labelCount: labelCountRef.getValue()
};


66120cookie-checkTypescript / React: RefValue