Home > Software design >  CreateFeatureSelector for nested state (combineReducers)
CreateFeatureSelector for nested state (combineReducers)

Time:07-13

The store for the app i am working on looks like this:

export const reducers: ActionReducerMap<State> = {
  auth: authReducer,
  settingsSlice: settingsReducer,
  incidentsSlice: incidentListReducer,
  networkStatus: networkStatusReducer,
  incidentSlice: incidentReducer,
};

What i am struggling with is creating feature selector for something inside of the incidentSlice, because that slice is very big and has a lot of nested slices.

For example: conferenceCallSlice is within incidentSlice, and i need to select callStatus inside of conferenceCallSlice. So i have tried this, amongst other stuff but i can't get anything to work:

export const selectIncidentSlice = createFeatureSelector('incidentSlice');
export const selectConferenceCall = createSelector(selectIncidentSlice, (state: any) => state.conferenceCall);
export const selectConferenceCallConfig = createSelector(selectIncidentSlice, (state: any) => state.conferenceCall.conferenceCall);
export const selectCallStatus = createSelector(selectConferenceCall, (state: any) => state.conferenceCall.callStatus);

For reference, this is the IncidentSlice reducer:

export interface IncidentState {
  currentIncident: CurrentIncidentState;
  statusBoard: StatusBoardState;
  stakeholders: StakeholderState;
  conferenceCall: ConferenceCallState;
}


export const reducer = combineReducers({
  currentIncident: currentIncidentReducer,
  statusBoard: statusBoardReducer,
  stakeholders: stakeholderReducer,
  conferenceCall: conferenceCallReducer,
});

Here is also conferenceCall Reducer:

export interface ConferenceCallState {
  conferenceCall: VideoCallRoomConfig;
  callStatus: CallStatus;
}

export const initialState: ConferenceCallState = {
  conferenceCall: conferenceCallConfigData,
  callStatus: CallStatus.NO_CALL,
};

What am i doing wrong?

CodePudding user response:

createFeatureSelector can only be used for top-level slices from the state tree. In your case, auth, settingsSlice, incidentsSlice, networkStatus, and incidentSlice.

To select state from the incidentSlice, the code snippet you shared should be correct (but you don't have to add extra types, these should be inferred.

export const selectIncidentSlice = createFeatureSelector<IncidentSliceState>('incidentSlice');
export const selectConferenceCall = createSelector(selectIncidentSlice, (state) => state.conferenceCall);
export const selectConferenceCallConfig = createSelector(selectIncidentSlice, (state) => state.conferenceCall.conferenceCall);
export const selectCallStatus = createSelector(selectConferenceCall, (state => state.conferenceCall.callStatus);

If you want that these selectors are generated, take a look at createFeature

  • Related