Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous state in the epic

Is there a way in an epic to receive previous state of the store? I feel you can't as the epic stands at the end of the Action -> Reducer -> Epic queue.

REMEMBER: When an Epic receives an action, it has already been run through your reducers and the state updated.

But maybe someone will suggest some solution to my problem:

I have an epic that handles downloading json which then is stored in the store. I though that another epic that will check what has changed would be good to dispatch a "new item" notification, but for that I need an access to the state prior to the store change:) maybe I should do it within the same epic?

like image 781
Lukasz 'Severiaan' Grela Avatar asked Oct 22 '25 09:10

Lukasz 'Severiaan' Grela


1 Answers

If you are using redux-observable > 1.0 you could use an operator like pairwise on the state$ stream.

eg:

const testEpic = (action$, state$) => {
  // Observable of [oldState, currentState)]
  const statePairs$ = state$.pipe(pairwise());
  return action$.pipe(
    ofType('TEST_ACTION'),
    withLatestFrom(statePairs$),
    map(([action, [ oldState, newState ]]) => { ..... })    
  );
}            
like image 116
WayneC Avatar answered Oct 24 '25 23:10

WayneC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!