Search code examples
reactjsreduxreact-reduxredux-toolkit

How can I access state of another slice in redux with redux-toolkit?


In my Redux store I have multiple slices and I would like to access the lang state of the settingsSlice inside the speciesSlice.

Here is a code sample of my slices:

const settingsSlice = createSlice({
  name: 'settings',
  initialState: { lang: 'en', theme: 'dark' },
  reducers: {
    ...
  },
});

const speciesSlice = createSlice({
  name: 'species',
  initialState: data[`vds-list-${HERE I WANT TO USE THE "lang" STATE OF THE SETTINGSSLICE}`],
  reducers: {
    ...
  },
});

Thus far I haven't found a solution so maybe it's just not possible?

I could just use one slice with all of the state inside of there, but I'd really like to separate different parts of the state in different slices.


Solution

  • Reducers, by definition, only have access to the section of state that they own. So, if I have {users: usersReducer, posts: postsReducer}, the usersReducer has no access to the posts state slice at all.

    See the Redux FAQ entry on "how can I share state between reducers?" for more details.