Skip to content

Commit

Permalink
feat: add types for buildSelector
Browse files Browse the repository at this point in the history
  • Loading branch information
sashtje committed Oct 6, 2023
1 parent 2137d81 commit ca19262
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { StateSchema } from '@/app/providers/StoreProvider';
import { ArticleSortField, ArticleType, ArticleView } from '@/entities/Article';
import { buildSelector } from '@/shared/lib/store';

export const getArticlesPageIsLoading = (state: StateSchema) =>
state.articlesPage?.isLoading || false;
Expand All @@ -23,3 +24,7 @@ export const getArticlesPageSearch = (state: StateSchema) =>
state.articlesPage?.search ?? '';
export const getArticlesPageType = (state: StateSchema) =>
state.articlesPage?.type ?? ArticleType.ALL;

export const [useArticleItemById] = buildSelector(
(state, id: string) => state.articlesPage?.entities[id],
);
12 changes: 8 additions & 4 deletions src/shared/lib/store/buildSelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import { useSelector } from 'react-redux';

import { StateSchema } from '@/app/providers/StoreProvider';

type Selector<T> = (state: StateSchema) => T;
type Result<T> = [() => T, Selector<T>];
type Selector<T, Args extends any[]> = (state: StateSchema, ...args: Args) => T;
type Hook<T, Args extends any[]> = (...args: Args) => T;
type Result<T, Args extends any[]> = [Hook<T, Args>, Selector<T, Args>];

export function buildSelector<T>(selector: Selector<T>): Result<T> {
const useSelectorHook = () => useSelector(selector);
export function buildSelector<T, Args extends any[]>(
selector: Selector<T, Args>,
): Result<T, Args> {
const useSelectorHook: Hook<T, Args> = (...args: Args) =>
useSelector((state: StateSchema) => selector(state, ...args));

return [useSelectorHook, selector];
}

0 comments on commit ca19262

Please sign in to comment.