Build an NgRx-style store: createReducer, memoized createSelector, queued dispatch and effects that recover
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
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 4
- code listings
- 8
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Build it bottom-up: action creators that carry a
type,on()andcreateReducerwith a type to reducer map, then a memoized selector that compares the state argument by reference and, separately, the input selector results by reference before calling the projector.
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.