react-command-palette icon indicating copy to clipboard operation
react-command-palette copied to clipboard

Allow providing callback prop to execute the command

Open iddan opened this issue 3 years ago • 8 comments

Is your feature request related to a problem? Please describe. My problem is the command property must be a function. Because of that, I must use this in it for the object to be testable.

Describe the solution you'd like I suggest introducing a new prop executeCommand: (command: Command) => void which will take the command object and execute it. That way the command object can contain only data and no this need to be used.

Additional context An example would be: Without executeCommand:

function go() {
    history.go(this.link);
}

const props = {
  options: [
    {
      name: "Go to example",
      link: "http://example.com",
      command: go
    },
  ],
};

With executeCommand:

const props = {
  options: [
    {
      name: "Go to example",
      link: "http://example.com",
    },
  ],
  executeCommand: (command) => {
    history.go(command.link)
  }
};

iddan avatar Sep 11 '20 16:09 iddan

@iddan can you describe what you are testing? The use of this should be optional within the command functions

asabaylus avatar Oct 07 '20 04:10 asabaylus

I'm testing the creation of the options provided to the command palette. If they could be data only I would be able to create them with a pure function which is much easier to unit test.

iddan avatar Oct 07 '20 08:10 iddan

Have you considered passing a noop function as commands then using onSelect to execute your function?

asabaylus avatar Oct 08 '20 02:10 asabaylus

No, I haven't. Seem like a little more complicated than the solution I proposed but it should do. If I understood it correctly, It will require creating custom code to the onSelect and updating the loading state manually.

iddan avatar Oct 08 '20 07:10 iddan

Yes, you'd be using onSelect much like the browser native drop down list box and matching on the returned object so that your function could be executed.

For context, I've periodically considered eliminating the inclusion of functions passed to the commands prop. It's really not required and breaks with native browser control conventions. However, I wanted a batteries included component the was easy to use.

asabaylus avatar Oct 08 '20 11:10 asabaylus

I agree it's a simpler approach. That is why I'm suggesting a more React-ive solution for the problem that separates data from function.

iddan avatar Oct 08 '20 17:10 iddan

@iddan I've got a few other enhancements to get to first but I'm open to a pull request

asabaylus avatar Oct 08 '20 20:10 asabaylus

I'll try to get around it.

iddan avatar Oct 11 '20 07:10 iddan