Search code examples
reactjsreduxreact-redux

How to pass an additional argument to useSelector


I am calling useSelector successfully from a component, which derives a product name from an id.

const productId = 25; // whatever

const productName = useSelector(
  (state) =>
    state.dashboard.dashboards.filter(
      ({ Id }) => Id === productId
    )[0].Name
);

However, my selector is dependent on productId, which I'm storing in a variable in the same file. I'd like to store this useSelector call in an external file so it can be shared. I tried the following, but id is undefined:

selectors.js

export const getProductNameById = (store, id) => {
  return store.dashboard.dashboards.filter(({ Id }) => Id === id)[0]
    .Name;
}

some_file.js

import { useSelector } from "react-redux";
import { getProductNameById } from "./selectors";

const productId = 25;
const productName = useSelector(getProductNameById, productId);

Solution

  • unfortunately, selector function accepts only store's state as argument. I would consider to use a currying approach to tackle the issue:

    export const getProductNameById = id => store => {
      return store.dashboard.dashboards.filter(({ Id }) => Id === id)[0]
        .Name;
    }
    

    some file

    import { useSelector } from "react-redux";
    import { getProductNameById } from "./selectors";
    
    const productId = 25;
    const productName = useSelector(getProductNameById(productId));