Pavel Voropaev
Pavel Voropaev

Reputation: 63

Pause rootEpic until persist completion

I'm using redux-persist and redux-observable in my application and noticed that my API calls wrapped in observable are happening before store state is restored. And restoration overrides fetched value with stale data. How could rootEpic be paused, while buffering, until persist/REHYDRATE action arrives?

Upvotes: 1

Views: 380

Answers (2)

Sebastian Sebald
Sebastian Sebald

Reputation: 16856

If you wanna wait until an "event" occurred you can use .skipUntil. For example:

const action$ = new Rx.Subject();

// In your epic
action$
  .skipUntil(action$.filter(({ type }) => type === 'hydrated'))
  .subscribe(x => console.log(x));

// "Rehydrate"
action$.next({ type: 'hello!' });
action$.next({ type: 'hello?' });
action$.next({ type: 'any body there?' });
action$.next({ type: 'hydrated' });
action$.next({ type: 'do' });
action$.next({ type: 'you' });
action$.next({ type: 'see' });
action$.next({ type: 'me' });
action$.next({ type: 'now' });
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

I guess, in order to not add this to all of your epics, you could .mergeMap() your root epic or something :)


After discussion in the comments below:

This issue might also occur with other middleware. Thus, it might be a better solution to not fire any actions until the re-hydration is done.

Upvotes: 1

jayphelps
jayphelps

Reputation: 15401

I'm not familiar with redux-persist, but it may or may not be important to note that the order in which you pass in middleware to redux matters. Some middleware needs to be before or after others. If this sounds relevant to your issue, you might try swapping them.

Upvotes: 0

Related Questions