Reputation: 19109
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
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
Reputation: 429
This should also work:
const productName = useSelector(getProductNameById(productId));
Upvotes: -5
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
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