From cb2aee37f7ae56736f453aa794d75953bca6f9bb Mon Sep 17 00:00:00 2001 From: Emmanuel Ogbizi-Ugbe Date: Sat, 12 Sep 2020 12:53:57 -0400 Subject: [PATCH] chore: add duck selector namespacing --- src/components/Provider.tsx | 2 +- src/createRootDuck.ts | 6 +++++- src/utils/combineSelectors.ts | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 src/utils/combineSelectors.ts diff --git a/src/components/Provider.tsx b/src/components/Provider.tsx index cdce9342..1c4ead5a 100644 --- a/src/components/Provider.tsx +++ b/src/components/Provider.tsx @@ -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({ children, diff --git a/src/createRootDuck.ts b/src/createRootDuck.ts index 59c97ca1..41fac2ec 100644 --- a/src/createRootDuck.ts +++ b/src/createRootDuck.ts @@ -1,4 +1,5 @@ import { combineReducers } from "./utils/combineReducers"; +import { combineSelectors } from "./utils/combineSelectors"; export function createRootDuck< D extends Duck[], @@ -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); diff --git a/src/utils/combineSelectors.ts b/src/utils/combineSelectors.ts new file mode 100644 index 00000000..69d22c5f --- /dev/null +++ b/src/utils/combineSelectors.ts @@ -0,0 +1,19 @@ +export function combineSelectors< + S, + T extends string, + P, + R, + N extends string, + Q extends string +>( + duckName: N, + selectors?: SelectorMapping, +): SelectorMapping | undefined { + if (!selectors) return; + const duckSelectors = {} as SelectorMapping; + for (const s of Object.keys(selectors) as Q[]) { + duckSelectors[s] = (state: S): R => + selectors[s](((state as unknown) as Record)[duckName]); + } + return duckSelectors; +}