A guide on assigning a boolean value to a property during an action using NGXS

Seeking guidance on how to set a boolean value inside an action in NGXS, as I am new to it.

Below is the interface I am working with:

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

Here is my state model configuration:

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

And this is the action implementation:

@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 am looking for a way to evaluate the daysToExpire property and set aboutToExpire to True if less than 61. Currently handling this logic in the template but aiming to move it to the action itself. Any suggestions would be greatly appreciated. Thank you!

Answer №1

If you want to incorporate it directly into the certificates map, here is an example:

ctx.patchState({
  certificates: certsResponse.certificates.map((cert) => ({
    ...cert,
    hasLowExpirationDays: cert.daysToExpire < 61 // Assigning the condition here
  })),
  filteredCertificates: certsResponse.certificates.map((cert) => ({
    ...cert,
    hasLowExpirationDays: cert.daysToExpire < 61 // Assigning the condition here
  })),
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ionic Angular 2 Form Development

Recently, I've encountered an issue while trying to submit a form using Ionic in Angular. <form method="post" class="form-horizontal" action="https://localhost:44370/Account/ExternalLogin"> <div> <p> <!-- ...

`Unable to access variable within the HTML file of a component in Angular`

I have been attempting to show the data from an array (which is populated in chat.component).. public matchesList = []; loadMatches() { ... if (result.success) { this.matchesList = result.matches_list.split(','); console.log(thi ...

Transforming a typical JSON file into a parent-child hierarchical JSON structure similar to the one utilized in d3's flare.json file format

My JSON file has a specific structure: { "a": "b", "c": "d", "e": { "f": "g", "h": "i" } } I want to transform it into the following structure: { "name": "Root", "parent": "null", "children": [ { ...

Tips for configuring the global API baseUrl for useFetch in Nuxt 3

Is there a way to globally set the baseUrl used in the useFetch composable, possibly through nuxt.config.ts? How can I prevent having to specify it in each individual useFetch call? ...

Issue: The formGroup function requires a valid FormGroup instance to be passed in. Data retrieval unsuccessful

My goal is to retrieve user data from a user method service in order to enable users to update their personal information, but I'm encountering an error. Currently, I can only access the "prenom" field, even though all the data is available as seen in ...

"What is the most effective way to utilize and integrate the `setValue` function from react-hook-form within a custom react hook

Struggling to pass setValue to a react hook? In my custom react hook, I need to set values in a form using react-hook-form's setValue. Yet, after migrating from v6 to v7, I'm having trouble figuring out the proper typing for this. This is how t ...

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

"Encountering a 'No overload matches this call' error while attempting to utilize a Vue Component in TypeScript

While attempting to implement a child component in a TypeScript Vue Component, I encountered the error message "No overload matches this call". Sharing this for the benefit of others, as finding a solution online proved challenging. import {ChildCompone ...

Is it possible that React useState is not allowing a default value to be set in this case?

In my chart component, I have the functionality to show/hide specific lines. To keep track of active lines, I maintain an array called activeKeys in a state. Initially, I populate this array by calling a function named getKeys, which takes an array of data ...

Is there a way to utilize Angular in identifying whether a given value corresponds with the value of a particular radio button within my application?

I have an array of lists that I need to display in radio buttons. Like this: https://i.stack.imgur.com/cmYgO.png https://i.stack.imgur.com/Zx4bm.png https://i.stack.imgur.com/jBTe3.png My goal is to have a checkbox that matches the values loaded from a ...

Learning how to use RestSharp's POST method in C# to send JSON data

Currently, I am in the process of testing a REST API using RestSharp. To post data and receive status (error, invalid, success) based on callback, I need to use the POST method. However, I am encountering an INVALID response with the message "Object refere ...

Issues encountered while building an Asp.net core 2/Angular 4 template

I've used the Asp.net core 2/Angular 4 template with the .Net core 2 SDK to create a project. When I use dotnet build or dotnet run, it doesn't generate a new dist folder for the client-side Angular project. My editor of choice is Visual Studio ...

Setting a value to an optional property of an inherited type is a simple task that can

export interface CgiConfiguration { name: string, value?: string } export interface CgiConfigurationsMap { [configurationName: string]: CgiConfiguration } const createCGI = <T extends CgiConfigurationsMap>(configurations: T) => configur ...

Utilize @agm/core in Angular 6 to load Google Maps by first retrieving latitude and longitude data from the server

I am currently developing a project in Angular6 that involves utilizing the "AGM - Angular Google Maps" library for mapping functionalities. One of the requirements is to dynamically draw the map based on latitude and longitude data fetched from the serve ...

angular2: The element 'Validators' is not recognized

When working with Angular2, I encountered an error in Visual Studio Code that is displayed with the following message: enter image description here Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module" ...

Avoid selecting primary key column in TypeORM查询

Is it possible to exclude primary key columns from being selected in TypeORM? I've tried using the select false option, but it doesn't seem to work for these specific columns. Could it be because they are essential for identifying the entity or b ...

Is there a specific CDK or CloudFormation resource I can use to import an entire DNS zone transfer?

We currently have all of our DNS entries stored outside of the AWS platform. Our goal is to transition to Route53, but in doing so, we want to establish a method that allows us to easily recreate the entire zone, including non-AWS entries. I've been e ...

The functionalities of model() and output() in Angular 18 appear to be malfunctioning

I am encountering an issue in my Angular 18 application while trying to implement a ModelSignal. The compiler is throwing an error message stating Can't bind to test since it is not provided by any applicable directives. I have carefully reviewed the ...

angular-universal | firestore-admin | code: 'app/invalid-authentication' | connection timeout

import * as admin from 'firebase-admin'; var serviceAccount = require('./keys/keyfile.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://test.firebaseio.com" }); var registrationT ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...