Using HTMLFormElement.reset() with Downshift and react-hook-form

917 views Asked by At

I'm using DownshiftJS to create an Autocomplete component using the useCombobox hook. It's all going well and testing with react-hook-form. Unfortunately, I've hit a problem where the reset function available within react-hook-form, which fires the HTMLFormElement.reset() method, does not trigger any state/input change within the Downshift component.

This means that when a user selects an item from the list (which triggers an event in the Autocomplete), clicks the reset button and then clicks the input again, the list is filtered to just the previously selected item. This is because the selected item is stored within a selectedItem internal state.

How can I get the reset method to trigger a change within Autocomplete component and clear the selectedItem state?

I've isolated the issue here.

1

There are 1 answers

1
NearHuscarl On BEST ANSWER

You can use React.useEffect to detect if the user hits the reset button and reset the selected items accordingly in your Autocomplete component

const [inputItems, setInputItems] = useState(options);
const {
  inputValue,
  ...
} = useCombobox({
  items: inputItems,
  ...
});

React.useEffect(() => {
  if (!inputValue) {
    // user resets value. Reset selected option
    setInputItems(options);
  }
}, [inputValue, options, setInputItems]);

Live Demo

Edit 64144984/using-htmlformelement-reset-with-downshift-and-react-hook-form