How to set a boolen property value inside of an action with NGXS

Viewed 62

I am new to NGXS and need to set a boolean value inside of an action and am not sure how to go about it.

Here is my interface:

export interface CertificateObject {
  certificateName: string;
  issueDate: Date;
  expiryDate: Date;
  thumbPrint: string;
  serialNumber: string;
  daysToExpire: number;
  aboutToExpire: boolean;
}

here is my state model:

export interface CertificateStateModel {
  certificates: CertificateObject[];
  filteredCertificates: CertificateObject[];
  searchLimitedStateMessage: string;
  emptyCertificateMessage: string;
  searchTerm: string;
}

and here is the action:

@Action(CertificateAction.GetAllCertificates)
  getAllCertificates(
    ctx: StateContext<CertificateStateModel>,
    action: CertificateAction.GetAllCertificates
  ) {

    ctx.dispatch(new Busy(true));
    return this.svc.getIACertificates().pipe(
      tap((certsResponse) => {
        ctx.patchState({
          certificates: certsResponse.certificates.map(cert => ({
            ...cert,
          })),
          filteredCertificates: certsResponse.certificates.map(cert => ({
            ...cert,
          })),
        });
        ctx.dispatch(new Busy(false));
      },
      (error: any) => {
        ctx.dispatch([
          new DisplayMessage({type: "error", list: [ "Get All Certificates Error", error.error ]}),
          new Busy(false)
        ]);
      })
    );
  }

I need to evaluate on the daysToExpire property and set aboutToExpire to True if < 61. I am currently doing this on the template and need to move the logic to the action but I am lost. Any help would be appreciated. Thanks

1 Answers

You can add it directly within certificates map like the following:

ctx.patchState({
  certificates: certsResponse.certificates.map((cert) => ({
    ...cert,
    aboutToExpire: cert.daysToExpire < 61 // <<<< assing it here
  })),
  filteredCertificates: certsResponse.certificates.map((cert) => ({
    ...cert,
    aboutToExpire: cert.daysToExpire < 61 // <<<< assing it here
  })),
});
Related