Skip to content

Commit

Permalink
fix: useThrottle not working
Browse files Browse the repository at this point in the history
  • Loading branch information
lawvs committed Nov 21, 2023
1 parent 2986bff commit f0b31f0
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/store/search.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
import { useCallback } from 'react'
import { useThrottle } from 'react-use'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useStore } from './store'

// Fix https://github.com/streamich/react-use/issues/2488
// Ported from https://hooks-guide.netlify.app/community/useThrottle
const useThrottle = <T>(value: T, limit = 200) => {
const [throttledValue, setThrottledValue] = useState(value)
const lastRan = useRef(Date.now())
useEffect(() => {
const handler = setTimeout(
function () {
if (Date.now() - lastRan.current >= limit) {
setThrottledValue(value)
lastRan.current = Date.now()
}
},
limit - (Date.now() - lastRan.current),
)
return () => {
clearTimeout(handler)
}
}, [value, limit])
return throttledValue
}

export const useSearchInput = () => {
const {
store: { searchInput },
Expand Down

0 comments on commit f0b31f0

Please sign in to comment.