Search code examples
reactjsantd

How do I detect if antd select search was not successful (in React)?


I'm using a searchable select component from antd and I need to detect if the search was unsuccessful (I need to add a UI button in that case). But, I can't seem to find any props for it in antd docs.

I've tried this:

<Select dropdownAlign={{ offset: [-15, 4] }}
              showSearch
              placeholder="Select a medicine"
              suffixIcon={
                // <HiOutlineArrowDown color="#29BCC1" />
                <img src={arrowdropdown} alt />
              }
              onChange={(e) => handleChange(e, "select", "medicine")}
              onSelect={(e) => setMed(e)}
              filterOption={(input, option) => {
                  if(!(option?.children?.toLowerCase()?.startsWith(input?.toLowerCase()))) {
                    console.log("no result")
                  }
                
                return option?.children?.toLowerCase()?.startsWith(input?.toLowerCase())
              }}
              value={med}
              className="c_select"
            >
              {props.medicine.data?.map((med, index) => (
                <Option value={med.id} key={index}>
                  {med.name}
                </Option>
              ))}
            </Select>

This is working, but the problem is that console.log("no result") logs about a 1000 times which is very inefficient. So, please guide me if there's a much better way to solve this issue. Thanks.

P.S: I'm using antd: 4.21.3 with react: 18.2.0.


Solution

  • Ok, so I added an onSearch prop to my Select component and passed in handleMedicineSearch function to it. The function is below:

    function handleMedicineSearch(value) {
        const filteredOptions = props.medicine.data?.filter((item) => {
          return item?.name?.toLowerCase()?.startsWith(value?.toLowerCase());
        })
    
        if(filteredOptions.length === 0) {
          setShowAddBtn(true);
        }
    
        else {
          setShowAddBtn(false);
        }
      }
    

    The line:

    if(filteredOptions.length === 0)

    is used to detect if the search was unsuccessful.