From b3a697caed0b2c93eb828995faa135f5d0fec2a7 Mon Sep 17 00:00:00 2001 From: sk1982 Date: Fri, 12 Apr 2024 05:52:51 -0400 Subject: [PATCH] fix: checking stored filter types in filter sorter --- src/components/filter-sorter.tsx | 47 +++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/components/filter-sorter.tsx b/src/components/filter-sorter.tsx index f5b6682..dfdd47d 100644 --- a/src/components/filter-sorter.tsx +++ b/src/components/filter-sorter.tsx @@ -480,6 +480,34 @@ const FilterSorterComponent = ); }; +const payloadValid = (payload: any, filterers: Filterers) => { + for (const p of ['sorter', 'pageSize', 'displayMode']) { + if (p in payload && !(payload[p] instanceof Set)) + return false; + } + + if ('currentPage' in payload && typeof payload.currentPage !== 'number') + return false; + + for (const filterer of filterers) { + if (!(filterer.name in payload)) continue; + const data = payload[filterer.name]; + console.log(filterer.name, data) + if (filterer.type === 'select' && !(data instanceof Set)) + return false; + if (filterer.type === 'slider' && !Array.isArray(data)) + return false; + if (filterer.type === 'dateSelect' && data !== undefined && ( + data.from === undefined || + (data.from !== undefined && !(data.from instanceof Date)) || + (data.to !== undefined && !(data.to instanceof Date)) + )) + return false; + } + + return true; +} + export const FilterSorter = (props: FilterSorterProps) => { const pathname = usePathname(); const localStateKey = `filter-sort-${pathname}`; @@ -494,7 +522,24 @@ export const FilterSorter = typeof v === 'object' && 'type' in v && v.type === 'set' ? new Set(v.value) : v); + payload = JSON.parse(stored, (k, v) => { + if (typeof v === 'object' && v !== null) { + if ('type' in v && v.type === 'set') + return new Set(v.value); + + const filterer = props.filterers.find(f => f.name === k); + if (filterer?.type === 'dateSelect') + return { + from: typeof v.from === 'string' ? new Date(v.from) : undefined, + to: typeof v.to === 'string' ? new Date(v.to) : undefined + }; + } + + return v; + }); + + if (!payloadValid(payload, props.filterers)) + payload = {}; setDefaultData(payload) } catch (e) {