user3771885
user3771885

Reputation: 53

NGRX correct usage of store selectors

I am using Ngrx in my application to store the state. Let's say my store has two items itemA and itemB. My componentX reacts to change in itemA and triggers a function which further does some more complex calculations which requires the current value of itemB

ComponentX {
    pi = 3.15;
    date = new Date();
    constructor(private appStore: Store<AppState>){}
    ngOnInit() {
         this.appstore.select(selectItemA).subscribe(
             (itemA) => someComplexFunction(itemA)
         )
    }
    someComplexFunction(itemA) {
        /* Requires itemB */
    }
}

The componentX however doesnt care when the itemB changes, it only requires the current value of itemB when itemA changes. I cannot remove itemB from my state as it is required by other components. What is the correct approach to write a selector in this case.

Upvotes: 0

Views: 268

Answers (1)

tlt
tlt

Reputation: 15291

you could make use of withLatestFrom operator.

something like withLatestFrom(this.appstore.select(selectItemB)) which will give you the B.

take a look at this example where the same thing is done in effects: https://gist.github.com/vteivans/da5adf19a94da9e32d27cb8b9d5b8884

(principle is the same)

Upvotes: 2

Related Questions