Btek
Btek

Reputation: 1

React-multi-select-dropdown

Trying to populate an array of options for React-multi-select-dropdown

   this.state.users.map((user) => {
      if (!this.state.options.includes(user.badgeId))
        this.state.options.push({ name: user.badgeId, id: user._id });
      return this.state.options;
    });

getting multiple values of the same in the options array.

    <Multiselect
      options={this.state.options} // Options to display in the dropdown
      //isObject={false}
      onSelect={this.onSelect} // Function will trigger on select event
      // onRemove={this.onRemove} // Function will trigger on remove event
      displayValue='name' // Property name to display in the dropdown options
    />

also once selected and form submitted the selected user.badgeId will need to be in its own array.

Upvotes: 0

Views: 788

Answers (2)

Btek
Btek

Reputation: 1

const b = this.state.users.map((obj, index) => ({
  name: obj.username,
  id: obj.badgeId,
}));

Upvotes: 0

Arthur Coelho
Arthur Coelho

Reputation: 73

The issue: your code checks if the value user.badgeId is not in the array options. Which always returns true because such array is populated with objects like: { name: user.badgeId, id: user._id }

A simple example:

const myArray = [{a: 1, b:'banana'}, {a: 2, b:'banana'}]

myArray.includes(1) // false

Instead you can use .find() to get a object in the array which has name === badgeId.

find() returns the value of the first element that satisfies the provided test function. This will be undefined if nothing is found.

Now we can search for and element in the array and do something if we find it. Like this:

const findResult = this.state.options.find((obj) => obj.name === user.badgeId);
if (typeof findResult === "undefined")
  // Do something

I'm not very good with the words so feel free to ask for clarification if this is confusing. Or you can see if this answer helps

Upvotes: 1

Related Questions