Andy Hoffman
Andy Hoffman

Reputation: 19109

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);

Upvotes: 41

Views: 33314

Answers (4)

Asmerom Fessehaye
Asmerom Fessehaye

Reputation: 1

This works fine for me.

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

Then you can call this using:

 const productName = useSelector(state => getProductNameById (id)(state));

Upvotes: 0

Ellis
Ellis

Reputation: 429

This should also work:

const productName = useSelector(getProductNameById(productId));

Upvotes: -5

Prakhar Varshney
Prakhar Varshney

Reputation: 715

Seems like the way to do this would be like this:

const productName = useSelector((state) => getProductNameById(state, productId));

This is the how redux docs tutorial seems to handle this. here

Upvotes: 55

buzatto
buzatto

Reputation: 10382

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));

Upvotes: 101

Related Questions