Use npm package for throttle hook
This commit is contained in:
parent
cd6fa2d68e
commit
c07937baee
5
app/package-lock.json
generated
5
app/package-lock.json
generated
@ -17172,6 +17172,11 @@
|
||||
"integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==",
|
||||
"dev": true
|
||||
},
|
||||
"use-throttle": {
|
||||
"version": "0.0.3",
|
||||
"resolved": "https://registry.npmjs.org/use-throttle/-/use-throttle-0.0.3.tgz",
|
||||
"integrity": "sha512-cgA3c+pe6V7cZ7pkLnYnWxXJub2AmksY7YTp/xiZzKesQyECJ1slWknVY2CVZOBf48avbZsAvJIDjO+aFu9+pw=="
|
||||
},
|
||||
"util": {
|
||||
"version": "0.11.1",
|
||||
"resolved": "https://registry.npmjs.org/util/-/util-0.11.1.tgz",
|
||||
|
@ -5,6 +5,7 @@
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"clean": "rm -rf build",
|
||||
"start": "razzle start",
|
||||
"build": "razzle build",
|
||||
"test": "razzle test --env=jsdom",
|
||||
@ -35,7 +36,8 @@
|
||||
"react-leaflet-universal": "^1.2.0",
|
||||
"react-router-dom": "^5.0.1",
|
||||
"serialize-javascript": "^2.1.1",
|
||||
"sharp": "^0.22.1"
|
||||
"sharp": "^0.22.1",
|
||||
"use-throttle": "0.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/plugin-syntax-jsx": "^7.7.4",
|
||||
|
@ -1,9 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useThrottle } from 'use-throttle';
|
||||
|
||||
import './autofillDropdown.css';
|
||||
|
||||
import { apiGet } from '../../../apiHelpers';
|
||||
import { useThrottledValue } from '../../../hooks/useThrottledValue';
|
||||
|
||||
interface AutofillDropdownProps {
|
||||
fieldName: string;
|
||||
@ -23,7 +23,7 @@ export const AutofillDropdown: React.FC<AutofillDropdownProps> = props => {
|
||||
const [options, setOptions] = useState<AutofillOption[]>(null);
|
||||
|
||||
// use both throttled and debounced field value as trigger for update
|
||||
const throttledFieldValue = useThrottledValue(props.fieldValue, 1000);
|
||||
const throttledFieldValue = useThrottle(props.fieldValue, 1000);
|
||||
|
||||
useEffect(() => {
|
||||
const doAsync = async () => {
|
||||
|
@ -1,22 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
export function useThrottledValue<V>(value: V, delay: number): V {
|
||||
const [throttledValue, setThrottledValue] = useState(value);
|
||||
let lastUpdated = useRef(Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
if(Date.now() - lastUpdated.current >= delay) {
|
||||
setThrottledValue(value);
|
||||
console.log('Updating to', value);
|
||||
lastUpdated.current = Date.now();
|
||||
}
|
||||
}, delay - (Date.now() - lastUpdated.current));
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [delay, value]);
|
||||
|
||||
return throttledValue;
|
||||
}
|
Loading…
Reference in New Issue
Block a user