Viking22
Viking22

Reputation: 561

ngrx store reducer configuration (angular 5)

I am using ngrx/store in my Angular 5 project. The Application state I store has multiple properties (slices). I want to individually be able to listen to changes to any of those properties. So in this case, should I be using multiple reducers - one for each state slice? Can it be achieved with one reducer? I am guessing it cannot be done, because with one reducer we will return a new copy of the entire state, rather than a slice. For e.g.

class AppState{
    private customerList: Customer [];
    private selectedCustomer: Customer;
    private countriesOperational: Country [];
}

I want to be able to listen to changes only on selectedCustomer, so I can do this:

store.select(state => state.selectedCustomer).subscribe((data) => {
})

Upvotes: 0

Views: 312

Answers (1)

Pawel Kiszka
Pawel Kiszka

Reputation: 850

First of all - there is no need to have several reducers. The new reducer should be implemented once you feel that your current reducer is too big / has multiple resposibilities / should be splitted due to some constrains.

Going back to your problem - lets say that your customer has 'id' property. And in the scenario that I want to present, the app will be showing list of current ids - from customerList. The customerList is going to be dynamically updated using ngrx actions (and the template will be listening to the changes).

In component:

public customerIds$: Observable<string[]>;

public ngOnInit(): void {
   this customerIds$ = this.store.select(
      state => state.customersList.map(customer => customer.id);
   );
}

In your template:

<div *ngFor="let id of customerIds$ | async">
   {{id}}
</div>

Right now (using async pipe) you connected your html template with ts component. So, lets say that you have a button that is adding a new customer to customersList:

<button (click)="addNewCustomer()">Add new customer</button>

And the addNewCustomer() method is dispatching an action, that is handled by your store. The result of an action is hiddin in reducer, sth like that:

... (reducer logic)
   case ADD_NEW_CUSTOMER:
      return {
        ...state,
        customersList: [...state.customersLits, action.payload]

Where:

Once the button is clicked, new customer id is displayed in the template

Upvotes: 1

Related Questions