If you want to include selectors in the buildAppSlice function, you can pass in selector functions as part of the options when creating a slice. I'll show you how you can define selectors together with your slice definition and then create a useSelectors hook that can utilize those selectors.
Here’s how you can modify buildAppSlice to accept selectors and bind them to the component using hooks:
Revised buildAppSlice with Selectors
import { useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import type { CreateSliceOptions, SliceCaseReducers } from '@reduxjs/toolkit';
import { bindActionCreators, createSlice } from '@reduxjs/toolkit';
/** Кастомная фабрика слайсов redux с биндом экшенов в dispatch и созданием reducerMap */
export const buildAppSlice = <
State,
CaseReducers extends SliceCaseReducers<State>,
Selectors,
Name extends string = string,
>(
options: CreateSliceOptions<State, CaseReducers, Name> & {
selectors?: Selectors;
},
) => {
const slice = createSlice(options);
/** Хук для бинд экшенов к dispatch */
const useActions = (): typeof slice.actions => {
const dispatch = useDispatch();
return useMemo(() => bindActionCreators(slice.actions, dispatch), [dispatch]);
};
/** Хук для получения селекторов слайса */
const useSelectors = <Key extends keyof Selectors>(
selectorKey: Key,
) => {
const selector = options.selectors?.[selectorKey];
if (!selector) {
throw new Error(`Selector "${selectorKey}" not found in slice "${slice.name}"`);
}
return useSelector((state: any) => selector(state[slice.name]));
};
/** Мапа редьюсера к его наименованию */
const reducerMap = {
[slice.name]: slice.reducer,
};
return {
...slice,
useActions,
useSelectors,
reducerMap,
};
};
Explanation of Changes:
-
Selector Definition:
- The
options parameter now includes an optional selectors property, allowing you to pass in a set of selectors when you define your slice.
-
useSelectors Hook:
- The
useSelectors function takes a key that corresponds to a specific selector passed in the slice.
- It retrieves the selector based on the key and applies it to the appropriate slice of state using
useSelector.
-
Error Handling:
- If the specified selector does not exist, an error is thrown to help with debugging.
Example Usage
Here's an example of how you can define a slice with selectors and use it in a component:
import React from 'react';
import { buildAppSlice } from './path-to-buildAppSlice';
// Define your slice with selectors
const mySlice = buildAppSlice({
name: 'mySlice',
initialState: { count: 0 },
reducers: {
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count -= 1;
},
},
selectors: {
selectCount: (state) => state.count,
// You can add more selectors here
},
});
// Your component
const MyComponent = () => {
const { increment, decrement } = mySlice.useActions();
const count = mySlice.useSelectors('selectCount'); // Using the selector defined in the slice
return (
<div>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
Summary
With these changes, you can define selectors directly within your buildAppSlice, and then use them in your components without needing to redefine them. This keeps related logic together and makes your code cleaner and easier to manage.