Fixed filter setting an resetting (one more time)

This commit is contained in:
Dmitriy Shishkov 2023-07-31 18:50:36 +03:00
parent 24bd39f689
commit 47fca02858
Signed by: dm1sh
GPG Key ID: 027994B0AA357688
2 changed files with 14 additions and 7 deletions

View File

@ -1,7 +1,7 @@
import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { FiltersType, URLDecoreFilters, URLEncodeFilters, defaultFilters } from '../utils/filters'
import { FiltersType, URLDecoreFilters, URLEncodeFilters, defaultFilters, excludeFilters } from '../utils/filters'
import { SetState } from '../utils/types'
function useFilters(initialFilters: FiltersType = defaultFilters): [FiltersType, SetState<FiltersType>] {
@ -11,7 +11,7 @@ function useFilters(initialFilters: FiltersType = defaultFilters): [FiltersType,
const appendFiltersSearchParams = (filters: FiltersType, replace = false) => (
setSearchParams(params => ({
...Object.fromEntries(params),
...excludeFilters(Object.fromEntries(params)),
...URLEncodeFilters(filters),
}), { replace })
)

View File

@ -19,7 +19,7 @@ const URLEncodeFilters = (filters: FiltersType) => (
filterNames.map(
fName => {
const v = filters[fName]
if (v) {
if (v || v === false) {
return [fName, v.toString()]
}
return [fName, undefined]
@ -32,21 +32,28 @@ const URLDecoreFilters = (params: URLSearchParams): FiltersType => {
const strFilters = Object.fromEntries(
filterNames.map(
fName => [fName, params.get(fName)]
).filter((p): p is [string, string] => p[1] !== null)
)
).filter((p): p is [FilterNames, string] => p[1] !== null)
) as Record<FilterNames, string>
return {
userId: fallbackToUndefined(Number.parseInt(strFilters['userId']), isInt),
category: fallbackToUndefined(strFilters['category'], isCategory),
metro: strFilters['metro'],
expired: fallbackToUndefined(strFilters['bookedBy'] === 'true', isBoolean),
expired: fallbackToUndefined(strFilters['expired'] === 'true', isBoolean),
}
}
const excludeFilters = <T extends FiltersType>(obj: T) => (
filterNames.reduce((cObj, fName) => {
delete cObj[fName]
return cObj
}, obj)
)
const convertFilterNames = (input: Record<string, string>) => ({
...input,
...(input['userId'] === undefined ? {} : { 'user_id': input['userId'] }),
})
export type { FilterNames, FiltersType }
export { defaultFilters, filterNames, URLEncodeFilters, URLDecoreFilters, convertFilterNames }
export { defaultFilters, filterNames, URLEncodeFilters, URLDecoreFilters, excludeFilters, convertFilterNames }