Options do not return to dropdown on reset form, only after choosing another option
Opened this issue · 2 comments
When I submit the form and use reset from react-hook-form to clear the form, the selected values from before do not get added to the list as part of reset, only when I choose another option it will refresh the dropdown list and add the previous selected values:
Steps to reproduce: choose some options, press submit, open dropdown to see previous selected options missing.
Expected: previous selected options return to the dropdown right away on reset
Am I doing some wrong?
Hi @joaoesp
I encountered the same problem even when not using react-hook-form. One potential solution is to provide the key prop to the Multiselect component, and this key should be modified each time you reset the form. This way, the Multiselect component will be re-initialized with its options when the form is reset.
For Ex:
import Multiselect from "multiselect-react-dropdown";
import { useState } from "react";
import { Controller, FieldValues, useForm } from "react-hook-form";
const App = () => {
const {
handleSubmit,
control,
reset,
formState: { isValid }
} = useForm();
const [counter,setCounter] = useState(0)
const categories = [
{ id: 0, name: "abc" },
{ id: 1, name: "def" },
{ id: 2, name: "ghi" },
{ id: 3, name: "jkl" }
];
const onSubmit = (article: FieldValues) => {
reset();
setCounter(prev=>{
return prev + 1
})
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="categories"
render={({ field: { value, onChange } }) => (
<Multiselect
key={counter}
options={categories.map(
(category) => category.id + " - " + category.name
)}
isObject={false}
avoidHighlightFirstOption={true}
onSelect={onChange}
onRemove={onChange}
selectedValues={value}
/>
)}
/>
<div>
<input
disabled={!isValid}
className="btn btn-dark"
type="submit"
value={"Submit"}
/>
</div>
</form>
);
};
export default App;
This is still the case for me. I don't have forms or Controllers in mine so a simple use of Multieselect in a div is enough to trigger it.
on my submit button i set the array passed to selectedValues to []
and it does nothing
This is very annoying especialy when you frequently select all the values and have nothing else to select to refresh the list.
A very ugly workaround is that i set a counter in my state, and then when i want to clear the list i increase this counter, and then integrated this counter into the key
prop for the Multiselect, which causes react to re-render it as a new element