Global Architect
Global Architect

Reputation: 163

How to access previous state and current state and compare them when you subscribe to store in ngrx?

In my component I subscribe to ngrx store which is triggered on change in the given state. I want to set the condition that if current and previous states are different then I do some action.

How to get previous state?

    this.store
      .select('testPortfolio')
      .subscribe(testPortfolio => {
        // if(testPortfolio.oldValue !== testPortfolio.currentValueValue) ??? ///something like this
        console.log(testPortfolio);
       });

Upvotes: 3

Views: 6446

Answers (1)

Vitalii Ilchenko
Vitalii Ilchenko

Reputation: 598

You can use distinctuntilchanged for that. In your case it will be something like:

this.store
  .pipe(
    select('testPortfolio'),
    distinctUntilChanged((prev, curr) => prev.value === curr.value)
  )
  .subscribe(testPortfolio => {
    console.log(testPortfolio); // called only when testPortfolio value has been changed
  });

Upvotes: 4

Related Questions