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

useMapReduce - feature request #338

Open
gap777 opened this issue May 20, 2023 · 1 comment
Open

useMapReduce - feature request #338

gap777 opened this issue May 20, 2023 · 1 comment

Comments

@gap777
Copy link

gap777 commented May 20, 2023

A few of our stimulus controllers ended up having a very similar structure:

  • attach input/change event listeners to a group of form inputs
  • when the inputs changed, evaluate their current values in light of a goal
  • update a target output (eg, submit button state, or innerText of a span) with results from evaluating the inputs

Examples:

  • monitor required inputs, and disable the submit button unless they all have a value set
  • monitor validatable inputs, and disable the submit button if any have an aria-invalid attribute set
  • monitor inputs under a section (tree item), and display the count of them having a non-blank value

We've come up with a way to significantly reduce the boiler plate of these using a map-reduce mixin:

export function useMapReduce(controller, { input, map, reduce, output })

each of configuration items is a callback function.

Used like this:

export default class PopulatedFieldsFormController extends Controller {
  static targets = ['output', 'input']

  connect() {
    super.connect()
    this.detectInvalidSetup()
    useMapReduce(this, {
      input: () => this.inputTargets,
      map: elementValue, // extract the value of each input
      reduce: fieldValues => fieldValues.filter(isPresent).length,
      output: populatedFieldCount => setElementValue(this.outputTarget, populatedFieldCount)
    })
  }

We're willing to share it with others, and wondering if you want it to be a part of your stimulus-use library.

@marcoroth
Copy link
Member

Hey @gap777, thanks for opening this issue and for proposing to upstream your useMapReduce function!

Currently stimulus-use is more a collection of behaviour/callbacks-related use-functions. But I really love the idea of extending it to more smaller use-utilities which can be commonly used in Stimulus controllers, like your useMapReduce.

I would love to see how that implementation might look like. Do you want to take a stab at it? Let me know if you need any help or have questions along the way!

Thank you!

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

2 participants