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

Viewed 14203

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.

2 Answers

I've managed to achieve this by simply importing the redux store object and have called getState() method.

so in speciesSlice reducer action you can do that:

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