NGRX - Store variable returning Undefined

Asked

Viewed 22 times

-1

I have a problem when I try to give Dispatch in a state and try to sign up for Oninit in my application.

Module Users:

import { StoreModule } from '@ngrx/store';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { reducer } from './state/user.reducer';
import { UserDetailComponent } from './user-detail/user-detail.component';

@NgModule({
  declarations: [UserDetailComponent],
  imports: [
    CommonModule,
    StoreModule.forFeature('users', reducer)
  ],
  exports: [
    UserDetailComponent
  ]
})
export class UserModule { }

This is my return:

export function reducer(state, action) {
  switch (action.type) {
    case 'SHOW_USER_NAME':
      console.log('existing state: ' + JSON.stringify(state));
      console.log('payload: ', action.payload);
      return {
        ...state,
        showUserName: action.payload
      };

    default:
      return state;
  }
}

This is the component where we perform Dispatch:

import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';

@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.scss']
})
export class UserDetailComponent implements OnInit {

  public show: boolean;

  constructor(private store: Store<any>) { }

  ngOnInit() {
    this.store.pipe(select('users')).subscribe(users => {
      this.show = users.showUserName;
    });
  }

  checkShowUserName(value: boolean) {
    this.store.dispatch({
      type: 'SHOW_USER_NAME',
      payload: true
    });
  }
}

Only that the variable users.showUserName comes Undefined.

Could you help me?

1 answer

0

I found out what it was:

A condition should be placed to verify that the return is null, as it is null even at the first moment. The state does not yet exist.

 ngOnInit() {
    this.store.pipe(select('users')).subscribe(
      users => {
        if (users) {
          this.show = users.showUserName;
        }
      });
  }

Att.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.