Can you write selectors that reference other state slices in Redux Toolkit?

Viewed 404

I'm fairly new to Redux/RTK so I'm still figuring things out.

The situation:

I have a locationsSlice which stores an array of ids (favIds) in the state.

I also have a forecastSlice which has an array of objects (forecastObjects).

My question:

I want to write a global selector that can return filtered forecast objects based on the ids in the locationsSlice. To do that, I need to reference another slice's state. What is the best way to do this?

I could write a hook for such logic, but is there a way to do this inside a slice? Is that bad practice?

1 Answers

I was able to achieve this with RTK's built-in createSelector documented here. Please let me know if this is an anti-pattern or anything.

// locationsSlice.js

import { createSelector } from "@reduxjs/toolkit";

// ...

const selectForecasts = (state) => state.locations.forecasts;
const favIds = (state) => state.user.favIds;

export const selectFavForecasts = createSelector(
  selectForecasts,
  favIds,
  (forecasts, ids) => {
    return forecasts.filter((forecast) => ids.includes(forecast.id));
  },
);
Related