Skip to content

Wrong item is focused when searching within array where items are re-ordered (fuzzy search) #4505

@NullPainter2

Description

@NullPainter2

Hi,

when I use async react-select with fuzzy searcher sometimes wrong items will be focused.

It is because react-select has internal reference (focusedOption) to item which it assumes will be selected by user, fuzzy result changes order of items to be more precise, and since react-select is trying to pick the same focused item it will not pick the first item but it will keep focusing the same item until it exists.

Repro:

type "prague" -> fuzzy result is ["prague 1", "prague 2" ...], focused item will be "prague 1" -> type prague "prague 4" -> fuzzy result will be ["prague 4", "prague 1", "prague 2" ...], focused item will still be "prague 1"

import ReactDOM from "react-dom";
import React, { Component } from 'react';
import Fuse from "fuse.js";

import AsyncSelect from 'react-select/async';

export const data = [
  {value: "prague1", label: "Prague 1, Street"},
  {value: "prague2", label: "Prague 2, Street"},
  {value: "prague3", label: "Prague 4, Street"},
  {value: "prague4", label: "Prague 8, Street"},
];

const fuzzySearch = new Fuse(data, {
  keys: ["label"],
});

const filterItems = (inputValue: string) => {
  // fuzzy search returns arrays with items which have different order
  return fuzzySearch
          .search(inputValue)
          .map(found => found.item)
}

const loadOptions = (inputValue, callback) => {
  // there is no need to delay result ...
  callback(filterItems(inputValue));
};

type State = {
  inputValue: string,
};

class Example extends Component<*, State> {
  state = { inputValue: '' };
  render() {
    return (
      <div>
        <pre>inputValue: "{this.state.inputValue}"</pre>
        <AsyncSelect
          cacheOptions
          loadOptions={loadOptions}
          defaultOptions
        />
      </div>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById("root"));

Metadata

Metadata

Assignees

No one assigned

    Labels

    menu-bugAddresses menu positioning, scrolling, or general interactions

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions