I need to make a request to the server each time user types in the Multiselect input to retrieve data based on the search query.
If i set the list with fixed values it works fine and filter the list.
import MultiSelect from "react-multi-select-component";
...
const options = [
{ label: "Grapes ", value: "grapes" },
{ label: "Mango ", value: "mango" },
{ label: "Strawberry ", value: "strawberry" },
];
const [selected, setSelected] = useState([]);
<MultiSelect
options={options}
value={selected}
onChange={setSelected}
labelledBy={"Select"}
/>
I tried to use filterOptions props on the MultiSelect. The problem is that when i press on the MultiSelect and start typing in the input it keeps making calls to the sever until I clear the value of the MultiSelect input. it stopped.
const [invoices,set_invoices] = useState([]);
const [selected, setSelected] = useState([]);
function test(options, filter) {
if (!filter) {
return options;
}
var data={'invoice_number':'22'}
axios.post('http://localhost:4000/get_invoice_by_number',data).then(
response => {
// The for loop below is to make the invoices objects like
// {label:'',value:''}
var temp_invoices=[];
for(var i =0;i<response.data.length;i++){
temp_invoices.push({
label:response.data[i].invoice_number,
value:response.data[i].invoice_number
})
}
// JSON.stringify(temp_invoices)
set_invoices(temp_invoices);
},error =>{
Swal.fire({
title: 'Error!',
text: 'Please Contact your software developer',
icon: 'error',
confirmButtonText: 'OK'
})
}
)
return options;
}
<MultiSelect
options={invoices}
value={selected}
labelledBy={"Select"}
onChange={setSelected}
filterOptions={test}
/>
You could make use of
filterOptionsprops MultiSelect component. The functions passed in the props will be triggered when user types in theMultiselectinput.But the
onChangewill be triggered only on selection of options.