2

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 Answer 1

2

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));
  },
);
2
  • 4
    Yes, this is the correct way to do it. Selectors are global in Redux, there is nothing preventing you from having a selector touch different slices. And it's very good to use createSelector when using filter as otherwise it will return a new reference every time which will create a lot of useless rerenders. Mar 19, 2022 at 11:16
  • Understood, cheers for commenting
    – JCraine
    Mar 19, 2022 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.