|
14 | 14 | * limitations under the License.
|
15 | 15 | */
|
16 | 16 |
|
17 |
| -import { useEffect, useMemo } from 'react' |
| 17 | +import { useEffect, useMemo, useRef } from 'react' |
18 | 18 | import { useHistory, useLocation } from 'react-router-dom'
|
| 19 | +import { getUrlWithSearchParams } from '@Common/Helper' |
19 | 20 | import { DEFAULT_BASE_PAGE_SIZE, EXCLUDED_FALSY_VALUES, SortingOrder } from '../../Constants'
|
20 | 21 | import { DEFAULT_PAGE_NUMBER, URL_FILTER_KEYS } from './constants'
|
21 | 22 | import { UseUrlFiltersProps, UseUrlFiltersReturnType } from './types'
|
@@ -47,7 +48,30 @@ const useUrlFilters = <T = string, K = unknown>({
|
47 | 48 | }: UseUrlFiltersProps<T, K> = {}): UseUrlFiltersReturnType<T, K> => {
|
48 | 49 | const location = useLocation()
|
49 | 50 | const history = useHistory()
|
50 |
| - const searchParams = new URLSearchParams(location.search) |
| 51 | + |
| 52 | + const isAlreadyReadFromLocalStorage = useRef<boolean>(false) |
| 53 | + |
| 54 | + const getSearchParams = () => { |
| 55 | + if (!isAlreadyReadFromLocalStorage.current && !location.search && localStorageKey) { |
| 56 | + isAlreadyReadFromLocalStorage.current = true |
| 57 | + const localStorageValue = localStorage.getItem(localStorageKey) |
| 58 | + if (localStorageValue) { |
| 59 | + try { |
| 60 | + const localSearchString = getUrlWithSearchParams('', JSON.parse(localStorageValue)) |
| 61 | + const localSearchParams = new URLSearchParams(localSearchString.split('?')[1] ?? '') |
| 62 | + |
| 63 | + history.replace({ search: localSearchParams.toString() }) |
| 64 | + return localSearchParams |
| 65 | + } catch { |
| 66 | + localStorage.removeItem(localStorageKey) |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return new URLSearchParams(location.search) |
| 72 | + } |
| 73 | + |
| 74 | + const searchParams = getSearchParams() |
51 | 75 |
|
52 | 76 | const getParsedSearchParams: UseUrlFiltersProps<T, K>['parseSearchParams'] = (searchParamsToParse) => {
|
53 | 77 | if (parseSearchParams) {
|
@@ -136,7 +160,9 @@ const useUrlFilters = <T = string, K = unknown>({
|
136 | 160 |
|
137 | 161 | const clearFilters = () => {
|
138 | 162 | history.replace({ search: '' })
|
139 |
| - setItemInLocalStorageIfKeyExists(localStorageKey, '') |
| 163 | + if (localStorageKey) { |
| 164 | + localStorage.removeItem(localStorageKey) |
| 165 | + } |
140 | 166 | }
|
141 | 167 |
|
142 | 168 | const updateSearchParams = (paramsToSerialize: Partial<K>) => {
|
|
0 commit comments