Here is a snippet for two arguments in different slices:
Slice A: jobSlice
export const rtkAllJobs = (state:RootState) => state.jobs.allJobs;
export const allJobRelatedCountsTest = createSelector(
[rtkMyUserSettings, rtkAllJobs],
(myUserSettings, allJobs) => {
const myMatches = myUserSettings ? allJobs.filter((job: Job) => job.isJobActive && +job.jobCumulativeScore > 0) : [];
let myMatchesCount = myUserSettings === undefined ? 0 : myUserSettings?.likedJobsArr! === null ? 0 : myMatches.length;
let allRelatedCounts = {
liked: myUserSettings === undefined ? 0 : myUserSettings.likedJobsArr === null ? 0 : myUserSettings?.likedJobsArr!.filter((likedJob: LikedJob) => likedJob.isJobActive).length ,
applied: myUserSettings === undefined ? 0 : myUserSettings.appliedJobsArr === null ? 0 : myUserSettings?.appliedJobsArr!.length,
matches: myMatchesCount,
}
return allRelatedCounts;
})
Slice B: individualSlice
export const rtkMyUserSettings = (state:RootState) => state.individual.userSettings;
Component I want to access the data in.
const jobMatchCount = useAppSelector(allJobRelatedCountsTest)
rtkAllJobs
accesses the job slice's value allJobs
then is passed into the createSelector([dependencies], (dependencies[0], dependencies[1] ...) => { // do the thing... return results})
rtkMyUserSettings
is stored in the individualSlice.tsx
file and just grabs the user's setting object which I need to pluck information from.
Nice! Another thing I learned: What if you have an argument that is not part of your redux store that you need to pass in to do stuff?
In my case, it was a translation hook that takes an array of numbers and assigns either english/french.
Below, we pass two arguments from our redux store data
and filter
+ a component based argument called t
// Assuming you have a state structure like this
const initialState = {
data: {},
filter: '',
};
// Selector functions
const selectData = (state) => state.data;
const selectFilter = (state) => state.filter;
// Selector factory function
const createSelectFilteredData = (t) => {
return createSelector(
[selectData, selectFilter],
(data, filter) => {
// Process data using filter...
const filteredData = // your processing logic here
// Use the t function
t(filteredData.name); // Assuming you want to call t with the 'name' property
return filteredData;
}
);
};
// In your component
const MyComponent = () => {
const t = useTranslateHook();
// Create the memoized selector using the factory function
const selectFilteredData = createSelectFilteredData(t);
const filteredData = useSelector(selectFilteredData);
// Render using filteredData
};