diff --git a/lib/AcqList/hooks/useFilters.js b/lib/AcqList/hooks/useFilters.js index 167c39d9..e266baa5 100644 --- a/lib/AcqList/hooks/useFilters.js +++ b/lib/AcqList/hooks/useFilters.js @@ -8,18 +8,21 @@ import { SEARCH_PARAMETER, } from '../constants'; -const useFilters = (resetData, initialFilters = {}, options) => { +const INITIAL_FILTERS = {}; +const OPTIONS = {}; + +const useFilters = (resetData, initialFilters = INITIAL_FILTERS, options = OPTIONS) => { const [filters, setFilters] = useState(initialFilters); const [searchQuery, setSearchQuery] = useState(''); const [searchIndex, setSearchIndex] = useState(''); const { skipTrimOnChange = false, - } = options || {}; + } = options; const applyFilters = useCallback( (type, value) => { - const newFilters = { ...filters }; + const newFilters = {}; if (Array.isArray(value) && value.length === 0) { newFilters[type] = undefined; @@ -27,13 +30,16 @@ const useFilters = (resetData, initialFilters = {}, options) => { newFilters[type] = value; } - setFilters(newFilters); + setFilters((currentFilters) => ({ + ...currentFilters, + ...newFilters, + })); resetData(); return newFilters; }, - [filters, resetData], + [resetData], ); const applySearch = useCallback( diff --git a/lib/AcqList/hooks/useLocationFilters.js b/lib/AcqList/hooks/useLocationFilters.js index b28e5d29..1ef43145 100644 --- a/lib/AcqList/hooks/useLocationFilters.js +++ b/lib/AcqList/hooks/useLocationFilters.js @@ -11,10 +11,19 @@ import { import { buildFiltersObj, buildSearch, + getFiltersCount, } from '../utils'; import useFilters from './useFilters'; -const useLocationFilters = (location, history, resetData, options) => { +const DEFAULT_FILTERS = {}; + +const useLocationFilters = ( + location, + history, + resetData, + options, + defaultFilters = DEFAULT_FILTERS, +) => { const { filters, searchQuery, @@ -32,7 +41,23 @@ const useLocationFilters = (location, history, resetData, options) => { () => { const initialFilters = buildFiltersObj(location.search); - setFilters(initialFilters); + setFilters((currentFilters) => { + const _defaultFilters = getFiltersCount(initialFilters) === 0 ? defaultFilters : {}; + + // If there are no filters in the URL, we need to add the default filters to the URL + if (Object.keys(_defaultFilters).length) { + history.push({ + pathname: '', + search: `${buildSearch(_defaultFilters, location.search)}`, + }); + } + + return { + ...currentFilters, + ..._defaultFilters, + ...initialFilters, + }; + }); setSearchQuery(initialFilters[SEARCH_PARAMETER] || ''); setSearchIndex(initialFilters[SEARCH_INDEX_PARAMETER] || ''); },