Skip to content

Commit

Permalink
chore: add duck selector namespacing
Browse files Browse the repository at this point in the history
  • Loading branch information
iamogbz committed Sep 12, 2020
1 parent b67ebcd commit cb2aee3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/components/Provider.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from "react";
import { useGetter } from "src/hooks/useGetter";
import { ActionTypes } from "src/utils/actionTypes";
import { createAction } from "src/createAction";
import { useGetter } from "src/hooks/useGetter";

export function Provider<S, T extends string, P>({
children,
Expand Down
6 changes: 5 additions & 1 deletion src/createRootDuck.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { combineReducers } from "./utils/combineReducers";
import { combineSelectors } from "./utils/combineSelectors";

export function createRootDuck<
D extends Duck<S, N, T, P, R, Q, U>[],
Expand All @@ -22,7 +23,10 @@ export function createRootDuck<
const duckName = duck.name;
rootDuck.actions[duckName] = duck.actions;
rootDuck.initialState[duckName] = duck.initialState;
rootDuck.selectors[duckName] = duck.selectors;
rootDuck.selectors[duckName] = combineSelectors(
duckName,
duck.selectors,
);
reducerMapping[duckName] = duck.reducer;
}
rootDuck.reducer = combineReducers(rootDuck.initialState, reducerMapping);
Expand Down
19 changes: 19 additions & 0 deletions src/utils/combineSelectors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export function combineSelectors<
S,
T extends string,
P,
R,
N extends string,
Q extends string
>(
duckName: N,
selectors?: SelectorMapping<S, R, T, P, Q>,
): SelectorMapping<S, R, T, P, Q> | undefined {
if (!selectors) return;
const duckSelectors = {} as SelectorMapping<S, R, T, P, Q>;
for (const s of Object.keys(selectors) as Q[]) {
duckSelectors[s] = (state: S): R =>
selectors[s](((state as unknown) as Record<string, S>)[duckName]);
}
return duckSelectors;
}

0 comments on commit cb2aee3

Please sign in to comment.