I am building a fairly complex search form with a few preset configurations for common searches.
The current set of filters are stored in a state variable filters
. This object is set whenever a field in the form is modified. When a preset is selected from a drop down, the filters are reset to that preset with this function:
function set_preset(preset: string) {
setCurrentPreset(preset);
if (preset) {
setFilters(FILTER_PRESETS[preset]);
}
}
However, to prevent confusion, when the user modifies the form from the preset, I would like the preset value to be reset to "Custom" in the drop down:
useEffect(() => {
setCurrentPreset('');
}, [filters]);
As is likely obvious, this simple solution does not function well, as set_preset
itself sets the filters, and the new filters will trigger the use effect, causing the displayed preset to reset to "Custom" again.
I would, essentially, like some way for the useeffect call to be triggered whenever filters are updated, except in the case that they are updated as part of a preset selection.
I know there are a few somewhat hacky ways I could attempt to solve this, such as by using an exterior boolean flag to keep track of when a preset is being set, but it feels like there must be a better way of resolving this.
2
Answers
I think what you want is to do is expand your
filter
to have aisPreset: boolean
value that you can check on. Then your code will look like:As mentioned by Unmitigated it would be a better idea to not use the useEffect for resetting the
currentPreset
, and use the onChange function for the filters to call setCurrentPreset to "Custom".