-
Notifications
You must be signed in to change notification settings - Fork 93
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: move table filter logic to custom useTableFilters hook usin…
…g useMemo
- Loading branch information
Showing
2 changed files
with
64 additions
and
48 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import { useMemo, useState } from 'react'; | ||
|
||
import useRawSearchParams from './useRawSearchParams'; | ||
|
||
const useTableFilters = () => { | ||
// This is our custom hook that updates the search params without a rerender. | ||
const [rawSearchParams, updateRawSearchParams] = useRawSearchParams(); | ||
|
||
const [tableFilters, setTableFilters] = useState( | ||
new Map() as Map<string, Set<string>>, // ColumnID -> Set<Values to remove> | ||
); | ||
|
||
useMemo(() => { | ||
const filters = Array.from(rawSearchParams.entries()) | ||
.filter(([key]) => key.startsWith('filter')) | ||
.reduce((accumulator: Map<string, Set<string>>, [key, value]) => { | ||
const columnId = key.split('_')[1]; | ||
if (!accumulator.has(columnId)) { | ||
accumulator.set(columnId, new Set()); | ||
} | ||
const valuesArray = value.split(',').map((item) => item.trim()); | ||
valuesArray.forEach((item) => accumulator.get(columnId)?.add(item)); | ||
return accumulator; | ||
}, new Map<string, Set<string>>()); | ||
|
||
setTableFilters(filters); | ||
}, [rawSearchParams]); | ||
|
||
const onClearFilter = (columnId: string) => { | ||
rawSearchParams.delete(`filter_${columnId}`); | ||
updateRawSearchParams(rawSearchParams); | ||
|
||
setTableFilters((oldFilters) => { | ||
const newFilters = new Map(oldFilters); | ||
newFilters.delete(columnId); | ||
return newFilters; | ||
}); | ||
}; | ||
|
||
const onToggleFilter = (columnId: string, filters: Set<string>) => { | ||
if (filters.size > 0) { | ||
rawSearchParams.set(`filter_${columnId}`, Array.from(filters).join(',')); | ||
} else { | ||
rawSearchParams.delete(`filter_${columnId}`); | ||
} | ||
updateRawSearchParams(rawSearchParams); | ||
|
||
setTableFilters((oldFilters) => { | ||
const newFilters = new Map(oldFilters); | ||
newFilters.set(columnId, filters); | ||
return newFilters; | ||
}); | ||
}; | ||
|
||
return { tableFilters, onClearFilter, onToggleFilter }; | ||
}; | ||
|
||
export default useTableFilters; |