Build an NgRx-style store: createReducer, memoized createSelector, queued dispatch and effects that recover

hardAbout 70 minutesUpdated CodingProangularngrxrxjsstate-managementselectorsmemoizationeffects
Not solved

Share this question

Problem

NgRx is the most common state library in large Angular apps, and interviews for those teams go beyond "what is a reducer". They ask why a selector does not recompute, in what order an effect sees an action, and why one failing HTTP call should not kill an effect forever. Build the core of NgRx on top of the small RxJS in the starter (keep it as it is: Observable, Subject, of, from, throwError, map, filter, tap, distinctUntilChanged, mergeMap, switchMap, catchError).

const load = createAction("[Users] Load");
const loaded = createAction("[Users] Loaded", props());
const users = createReducer([], on(loaded, (_, { users }) => users));
const load$ = createEffect((actions$) =>
  actions$.pipe(ofType(load), switchMap(() => from(api.getUsers()).pipe(map((users) => loaded({ users }))))),
);
const store = createStore({ users }, { effects: { load$ } });
store.select((s) => s.users).subscribe(console.log); // [] now, the list later
store.dispatch(load());

Ref. UR-1455 · © UIRound · uiround.com/questions/build-an-ngrx-style-store-createreducer-memoized-createselector-queued-dispatch-and-effects-that-recover

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment