4

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?

Lukasz 'Severiaan' Grela
  • 6,078
  • 7
  • 43
  • 79

1 Answers1

9

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 ]]) => { ..... })    
  );
}            
Neil Pelow
  • 48
  • 5
WayneC
  • 5,569
  • 2
  • 32
  • 43
  • For me both - oldState and newState show new value in the state. Why can this be happening? – jayarjo Feb 06 '20 at 16:00
  • @jayarjo it will likely be caused by another epic (attached sooner) reacting to the same action type and dispatching something that modifies the state. So your old/new states will likely be capturing that change. – Tom Jan 27 '22 at 22:42