Skip to content

options fail to rerender when changed after onSelect #253

@angelzbg

Description

@angelzbg

Currently I want to sort the options in order to show the selected options first in the list and then the other available options.
My code for this task is:

    const { options, selected } = useMemo(() => {
      if (!Array.isArray(value)) {
        return { options: [], selected: [] };
      }

      const options = items
        .slice()
        .sort((a, b) => value.some((val) => val == b.id) - value.some((val) => val == a.id));

      // const selected = value.map((v) => ({
      //   id: v,
      //   name: items.find((i) => i.id == v)?.name
      // }));

      const selected = options.filter((o) => value.some((v) => v == o.id));

      return { options, selected };
    }, [items, value]);

The props are used like so:

            <Multiselect
              id={field.ID}
              options={options}
              hideSelectedList
              displayValue="name" // key from VALUES to display
              selectedValues={selected} // needs the whole object for preselecting values
              showCheckbox={true}
              // showArrow={true}
              // customArrow={true}
              placeholder={value?.length ? `${value.length} selected` : field.PLACEHOLDER}
              avoidHighlightFirstOption={true}
              onSelect={(selectedList) => {
                setFieldValue(
                  field,
                  selectedList.map((i) => i.id)
                );
              }}
              onRemove={(selectedList) => {
                setFieldValue(
                  field,
                  selectedList.map((i) => i.id)
                );
              }}
              disable={disabled}
            />

After checking the console logs on each render the 'options' and the 'selected' values are being updated, but the option list of the Multiselect is lagging one render behind. Basically is not changing the order of the options visually.
Strangely enough this works perfectly for onRemove but fails to rerender after onSelect.

In my test case I have 1 preselected option,, once I select a second option it doesn't show it sorted but the value is really updated in the logs. Once I close the dropdown by clicking outside and then opening the dropdown again it is shown sorted. But this is a problem, because ofc the user wouldn't like to have to reopen the dropdown on each and every select he makes.

Is this a bug? I think it's a bug and it's a deal breaker for the project I have implemented the library in.

Is there a way I can fix this or can someone check the issue and release a bug fix?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions