Unable to access the property 'IdEvento' through destructuring in 'this.store.selectSnapshot' operation

Hey there, I'm encountering an issue while trying to display a modal upon button click. The error message I receive is "ERROR TypeError: Cannot destructure property 'event id' of 'this.store.selectSnapshot (...)' as it is undefined." What might be causing this problem?

https://i.sstatic.net/eL6UZ.png

This function is supposed to trigger the modal:

  handleListar(item: IGeneral) {
    this.store.dispatch(new FormActividadSolContainerActions.ListarDatosHistorial({ IdEvento: item.nro }));
    const dialogRef = this.dialogService.openXL(ModalHistorialCambiosComponent);    
  }

The line triggering the error:

  private loadGridHistorial = () => {
    const { IdEvento: IdEvento } = this.store.selectSnapshot(CONTAINER_STATE_TOKEN);
    this.store.dispatch(new ContainerActions.ListarDatosHistorial({ IdEvento }));
  }

Here's my model:

export class FormHistorialModel {  
  title = 'Detalle Del Historial';   
  gridHistorial: { loading: boolean; definition: IDataGridDefinition; source: IDataGridSource<any> } = {
    loading: false,
    definition: {
      columns: [
        { label: 'Numero de Evento', field: 'idEvento' },
        { label: 'Nombre de Evento', field: 'nombreEvento' },
        { label: 'Tipo de Evento', field: 'tipoEvento' },
        { label: 'Fecha del Cambio', field: 'fechaCambio' },
        { label: 'Cambio y Motivo', field: 'cambioyMotivo' },
        { label: 'Usuario', field: 'usuario' },          
      ]
    },
    source: {
      items: [],
      page: 1,
      pageSize: 10,
      total: 0
    }
  };
  formType = FormType.CONSULTAR;
  IdEvento: number = null;    
}

Action:

  export class ListarDatosHistorial {
    static readonly type = '[FORM-ACTIVIDAD-SOL-CONTAINER] ListarDatosHistorial';
    constructor(public payload: { IdEvento: number }  ) { }
  }

State:

  listarHistorialSolicitudesBegin = (
    ctx: StateContext<FormHistorialModel>
  ) => {
    const state = ctx.getState();
    ctx.patchState({
      gridHistorial: {
        ...state.gridHistorial,
        loading: true
      },
    });
  }

  ...
  (remaining content unchanged)
  ...

  @Action(ContainerActions.ListarDatosHistorial)
  asynclistarHistorial(
    ctx: StateContext<FormHistorialModel>,
    { payload }: ContainerActions.ListarDatosHistorial
  ) {
    this.listarHistorialSolicitudesBegin(ctx);
   
    return this.historialService.ListarHistorial(payload.IdEvento).pipe(
      tap(response => {
        
        this.listarHistorialSolicitudesSuccess(ctx)(
          response.data || []
        );
      }),
      catchError(err => {
        this.listarHistorialSolicitudesError(ctx)(err);
        return throwError(err);
      })
    );
  }

Service: https://i.sstatic.net/t7xOp.png

Answer №1

My understanding may not be completely accurate, but it seems that selectSnapshot only provides a callback of the entire state object. To retrieve the specific value you need, you must reference the particular piece of state.

An example can be found on ngxs.io/concepts/select#snapshot-selects

@Injectable()
export class CustomInterceptor implements HttpInterceptor {
  constructor(private store: Store) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.store.selectSnapshot<string>((state: AppState) => state.auth.token);
    req = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });

    return next.handle(req);
  }
}

Answer №2

To begin troubleshooting, I suggest inserting a breakpoint or debugger statement to examine the snapshot being returned:

private loadGridHistorial = () => {
    const state = this.store.selectSnapshot(CONTAINER_STATE_TOKEN);
    debugger; // Take a closer look at the state variable
    this.store.dispatch(new ContainerActions.ListarDatosHistorial({ IdEvento }));
  }

If the above method is not effective, consider changing from using the state token to calling the state class name

this.store.selectSnapshot(ContainerState);

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

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

By specifying the union type being used, the TypeScript compiler is informed

Imagine I have the following type: type TMyType = { a: string; b: number; c: number; d?: SpecialTypeA | SpecialTypeB | SpecialTypeC; } How can I specify in typescript that I am aware of the type of d in my (React) child components? I am hoping f ...

How to extract a value from [object object] in Angular4

In my previous question, I shared the code below: getUserRole() { const headers = new Headers(); headers.append('Authorization', `Bearer ${this.getToken()}`); console.log(this.getToken()); const options = new RequestOptions({ headers: he ...

Sending information to a deeply nested child component in Angular 4

Here is the structure of components in my Angular application: app.component.html units.component.html section.component.html {{appData.title}} I have created "appData" in the app.component.ts and now I want to access it in the third level child co ...

JavaScript code for sorting a list of objects alphabetically according to a different list

I am looking to alphabetically sort a list of objects based on another list of characters and the 'name' property. Below is the sorting order I would like to use: const SortingArray = [['a','á','à','â', ...

Explore all user-defined properties of a specified type using the TypeScript Compiler API

Consider the following model structure: interface Address{ country: string; } interface Author{ authorId: number; authorName:string; address: Address; } interface Book{ bookId:string; title: string; author : Author; } I want to iterate th ...

The possibility exists that the onClick function may be null

I am encountering an issue with a props function that is showing an error message stating that the object may be null. import {Dropdown} from "react-bootstrap"; interface GenreButtonProps { key: number; id: number | null; genre: strin ...

The object in an Angular 11 REACTIVE FORM may be null

I am looking to incorporate a reactive form validation system in my application, and I want to display error messages based on the specific error. However, I am encountering an error that says: object is possibly 'null'. signup.component.html &l ...

Discovering the cause of the "Module not found" error for nrwl packages

In my project, I have integrated nrwl.io. I have set up multiple libraries: ng g lib rest //successfully created ng g lib services //successfully created ng g lib models //created without errors, but encountering "Cannot find module" issue later on! Ev ...

The scrollbar track has a habit of popping up unexpectedly

Is there a way to prevent the white area from showing up in my divs where the scroll bar thumb appears? The issue seems to occur randomly on Chrome and Safari. https://i.sstatic.net/jFzTf.png This is the div in question .column-content{ height:60vh; ...

Ensure that all images uploaded are adjusted to fit the consistent dimensions within a card

I am in the process of creating a form that allows users to upload various images, which will then be displayed as cards on a website. After uploading an image, the size of the card automatically adjusts to fit the image, ensuring that all cards maintain ...

The landscape of type definitions is evolving within TypeScript

Would someone please clarify why this is happening? Is it a bug or did I overlook something? function checkString<T>(arg:T):boolean { return (typeof(arg)==='string') ? true : false; } let myEcho; myEcho = checkString; let myInt :numb ...

When communicating with the Rails 5 API, ensure that the post request in Angular 4/Ionic 2 includes the necessary `registration` field

Within my Ionic2/Angular4 application, I have implemented the following method: const body = JSON.stringify(values); let headers = new Headers(); headers.append('Content-Type', 'application/json'); console.log(body) return this.http. ...

What is the process for eliminating a field from an Angular Reactive Form?

I am working with an Angular form that needs to be sent to the API and it includes 4 fields: username, email, password, and confirmpassword. However, I only want to send three of them - username, email, and password. Does anyone have any suggestions on ho ...

I'm looking to incorporate a module from another component (Next.js, React.js) into my project

I need to implement the "StyledSwiperPagination(swiper-pagination-bullet) at SwiperImages.tsx" in "index.tsx". The problem is that when I added <StyledSwiperPagination /> in index.tsx, nothing appeared on the screen. Lorem ipsum dolor sit amet, co ...

Configuring Angular 4 with ASP.NET MVC and Webpack in the .NET Framework

I'm in need of guidance on how to set up a .NET MVC project with Angular 4 and webpack. Can someone provide a detailed, step-by-step solution? ...

What could be causing me to receive a 404 error when trying to reload localhost in Angular?

Despite searching for solutions to my issue, I have not found any that have helped me. I have set up my routing in app-routing.module.ts: const routes: Routes = [ { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] }, ...

Angular 10: Customize Paypal button to open a new window when selecting "Pay by debit or credit card" option

In my Angular 10 app, I have successfully implemented a Paypal button. However, there is an issue where the "Paypal" button opens a new window while the "Pay by debit or credit card" option opens an inline form. This behavior mirrors what is seen at https: ...

Can anyone suggest a more efficient method for specifying the type of a collection of react components?

Picture this scenario: you are extracting data from an API and creating a list of Card components to be displayed in a parent component. Your code might resemble the following: function App() { let items = [] // How can I specify the type here to avoid ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...