Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I create a selector that takes an argument? #11

Open
peidongbiao opened this issue Jul 16, 2023 · 2 comments
Open

How do I create a selector that takes an argument? #11

peidongbiao opened this issue Jul 16, 2023 · 2 comments

Comments

@peidongbiao
Copy link

peidongbiao commented Jul 16, 2023

As the title says, how do I create a selector that takes an argument? just like this in ReselectJS

204bbdd3-2224-455f-bbd8-3c4cca23b8e3

@brianegan
Copy link
Owner

You have a few options. First, you can write a fuction that creates a selector. Building on the example in the readme, let's say you wanted to make the affordable products selector configurable:

Selector<AppState, List<Product>> createAffordableProductsSelector(double price) {
  return createSelector1(
    productsSelector,
      (products) => products.where((product) => product.price < price),
    );
}

// Usage
final affordableProductsSelector = createAffordableProductsSelector(10.00);
final affordableProducts = affordableProductsSelector(appState);

The other option: Although a selector only takes in 1 parameter, that parameter can be anything you want. It can be a class that holds multiple values, or a Dart 3 record.

typedef Params = (AppState state, double price);

final affordableProductsSelector = createSelector1<Params, (List<Product>, double), List<Product>>(
    (params) => (productsSelector(params.$2), params.$2),
    (result) => result.$1.where((product) => product.price < result.$2),
);

@jamesncl
Copy link
Contributor

Great answer, I think it would be helpful to add this to the README - see my pull request. I amended the second example - I'm pretty sure it should be productsSelector(params.$1) instead of productsSelector(params.$2)

brianegan pushed a commit that referenced this issue May 14, 2024
* Added an example of creating a selector with arguments to README

Based on [#11](#11)

* Fixed incorrect record index in second example of selectors with arguments in README
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants