'Reuse selectors inside reducer with redux toolkit
Is there any way to reuse selectors created by createSelector inside of reducers?
My use case is that I have a graphql mutation (createAsyncThunk) inside of a slice. The function returns only a referenced id, so I will have to filter the passed in state (which is not the root state, but already the slice of it) by the referenced id.
I do have my selectors in place which do have that functionality already, but neither can I use useAppSelector nor can I call the selector since it expects the root state.
extraReducers: (builder) => {
// This is from an asyncThunk
builder.addCase(acknowledgeAllTenantViolations.pending, (state, action) => {
// Action will pass me a referenced id, I now need to update all violations matching that id
}
Those are typical selectors I would like to reuse
export const selectViolationsNotAcknowledged = createSelector(
[selectAllViolations],
(violations) => violations.filter((violation) => !violation.acknowledged)
)
export const selectViolationsByTenant = createSelector(
[selectViolationsNotAcknowledged, (state: RootState, tenantId: string) => tenantId],
(violations, tenantId) => violations.filter((violation) => violation.tenantId===
tenantId)
)
If that is not possible is there any way to be handling the state.entities better? They are key object pairs and not very accessible since you will need to use Object.entries(state.entities). I found out that I can do something like
extraReducers: (builder) => {
// This is from an asyncThunk
builder.addCase(acknowledgeAllTenantViolations.pending, (state, action) => {
const {selectAll} = deviceViolationEntityAdapter.getSelectors<typeof state>((state) => state)
}
But then I end up at the place where I need to recreate those selectors or at least have them around twice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
