Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use useAppSelector with nested combineSlices? #4477

Closed
devanecondition opened this issue Jun 22, 2024 · 4 comments
Closed

How to use useAppSelector with nested combineSlices? #4477

devanecondition opened this issue Jun 22, 2024 · 4 comments

Comments

@devanecondition
Copy link

Sorry if this is in the docs somewhere, I couldn't find it. If have a slice with selectors, like this:

export const ui = createSlice({
  name: 'ui',
  initialState: initialState,
  reducers: {
     setIsDirectoryDrawerOpen : (state, {payload}: PayloadAction<boolean>) => {
      state.isDirectoryDrawerOpen = payload;
    },
  },
  selectors: {
    getIsDirectoryDrawerOpen: state => state.isDirectoryDrawerOpen,
  },
});

and that slice is in a nested part of the state, like this:

const state1Reducer = combineSlices(
  ui,
  // other state 1 slices
);

const state2Reducer = combineSlices(
  // state 2 slices
);

const rootReducer = combineSlices({
  state1: state1Reducer,
  state2: state2Reducer,
});

At the component level, if I wanna call getIsDirectoryDrawerOpen, do I have pass in the nested state to the selector like this?

const isDirectoryDrawerOpen = useAppSelector(state => getIsDirectoryDrawerOpen(state.state1));

Just wondering if there's not a way to set it to just do useAppSelector(getIsDirectoryDrawerOpen);

Thanks!

@markerikson
Copy link
Collaborator

The slice selectors give you the slice state as the argument, but they default to assuming that the slice itself is already in rootState[slice.name] (in this case, state.ui), and accept the root state as the argument.

So, you can already pass getIsDirectoryDrawerOpen directly to useAppSelector.

@EskiMojo14
Copy link
Collaborator

when your slice is nested, you need to call .getSelectors with a custom selector, instead of using .selectors.

For example, your case would be:

const { getIsDirectoryDrawerOpen } = ui.getSelectors((state: RootState) => ui.selectSlice(state.state1))

@markerikson
Copy link
Collaborator

Whoops, my bad, I misread the original question, sorry!

@devanecondition
Copy link
Author

Sweet, getSelectors works great. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants