jakezatecky / react-dual-listbox

A feature-rich dual listbox for React.
https://jakezatecky.github.io/react-dual-listbox/
MIT License
110 stars 59 forks source link

onChange does not pass numeric values #73

Closed jeloooooo closed 5 years ago

jeloooooo commented 5 years ago

Do you have any sample code for loading the options dynamically via fetch/axios?

I currently have the code below and the options are being loaded into state. The issue is that whenever I'm selecting an option, it doesn't get removed in the Available section, that's why I'm thinking that it might have something to do with the way I'm loading the options in state.

this.state = {
            loading: true,
            selected: [],
            options: [],
        };

.......

componentDidMount() {
        fetch(API)
          .then(response => response.json())
          .then(data => this.setState({ options: data.project_templates }));
      }

Thanks

jakezatecky commented 5 years ago

Somewhat related to #63. I created a quick example that dynamically fetches the options and updates the state. It does not appear to have any issues:

import React from 'react';
import DualListBox from 'react-dual-listbox';
import 'react-dual-listbox/lib/react-dual-listbox.css';

class Widget extends React.Component {
  state = {
    options: [],
    selected: [],
  };

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        options: [
          { value: 'one', label: 'Option One' },
          { value: 'two', label: 'Option Two' },
        ],
      });
    }, 500);
  }

  onChange = (selected) => {
    this.setState({ selected });
  };

  render() {
    const { options, selected } = this.state;

    return (
      <DualListBox
        options={options}
        selected={selected}
        onChange={this.onChange}
      />
    );
  }
}

export default Widget;

Could you try modifying the above CodeSandbox example to replicate your behavior?

jeloooooo commented 5 years ago

Hi jakezatecky this CodeSandbox example replicates the behavior that I'm describing.

jakezatecky commented 5 years ago

@jeloooooo in your example the options being returned do not have the value attribute (they have the id attribute instead). So, when the listbox component tries to use option.value it resolves to undefined. Therefore, all the items move over when a single option is selected because all of them have a value of undefined.

A simple mapping from id to value would resolve that issue, but I noticed that the library is having an issue with numeric values (because at some point they get internally converted to a string). That is not supposed to happen and I will implement a fix for that.

The following modification of your example works, though because of the issue I noted above I had to convert the values to strings. Again, I will set about creating a fix for that.

jeloooooo commented 5 years ago

Awesome @jakezatecky ! Looking forward to v2. Thanks