Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter default values #293

Merged
merged 2 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions src/components/filter/useFilter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { useDebounce } from '@aboutbits/react-toolbox'
import { ChangeEventHandler, useEffect, useMemo, useRef, useState } from 'react'
import {
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'

export type FilterOptions = {
/** Whether to debounce and the debounce interval in milliseconds.
Expand All @@ -25,7 +32,11 @@ export function useFilter<TElement extends HTMLElement & { value: unknown }>() {
}
return 0
}, [options?.debounce])
const elementRef = useRef<TElement>(null)
const [element, setElement] = useState<TElement | null>(null)

const elementRef = useCallback((element: TElement | null) => {
setElement(element)
}, [])

const settingNewValueRef = useRef(false)

Expand All @@ -43,10 +54,10 @@ export function useFilter<TElement extends HTMLElement & { value: unknown }>() {
}, [debouncedInternalValue, setValue])

useEffect(() => {
if (elementRef.current && !settingNewValueRef.current) {
elementRef.current.value = value
if (element && !settingNewValueRef.current) {
element.value = value
}
}, [value])
}, [value, element])

const onChange: ChangeEventHandler<TElement> = (e) => {
settingNewValueRef.current = true
Expand Down
6 changes: 5 additions & 1 deletion src/examples/List.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,11 @@ export const ListWithFilter: Story = () => {
const numberOfTotalItems = 1000
const numberOfItemsPerPage = 5
const [page, setPage] = useState(1)
const [filter, setFilter] = useState({ role: '', department: '', search: '' })
const [filter, setFilter] = useState({
role: 'ADMIN',
department: '',
search: '',
})
const content = useMockedList(numberOfTotalItems).filter(
(item) =>
item.name.includes(filter.search) &&
Expand Down