How to display content of store?

Viewed 41

I created the following store:

imports: [BrowserModule, StoreModule.forRoot({ bugs: bugsReducer })],

Then i created reducer and action:

const addBugAction = createAction('[bbb] add bug', props<Bug>());

export const bugsReducer = createReducer(
  { bugs: [] },
  on(addBugAction, (state, bug) => ({
    bugs: [...state.bugs, bug]
  }))
);

I also have a selector:

const selectState = (state: any) => state;
export const selectBugs = createSelector(
  selectState,
  (state: any) => state.bugs
);

Finally i try to display the content of the Store into the HTML template:

@Component({
  selector: 'app-root',
  template: `
    <div *ngIf="bugs$ | async">
      bugs: {{ (bugs$ | async).bugs }}
    </div>
  `
})
export class AppComponent {
  constructor(private store: Store<any>) {
    this.store.dispatch(
      addBugAction({
        x: 100,
        y: 200
      })
    );

    setTimeout(() => {
      const bugs$ = this.store.pipe(select('selectBugs'));
      bugs$.subscribe(console.log);
    }, 1000);
  }
}

But i see just a white screen. The console displays

undefined

Could you help me displays the content of the Store? In other words i need display bugs value on the screen.

Live example is HERE

1 Answers

You just need to remove the quotes from the selector in order to see the console log like this:

const bugs$ = this.store.pipe(select(selectBugs));

To see the value on the page, create a TypeScript class variable to store the value and bind it in the template.

I have updated your code here.

Related