Use npm package for throttle hook

This commit is contained in:
Maciej Ziarkowski 2020-01-09 13:07:50 +00:00
parent cd6fa2d68e
commit c07937baee
4 changed files with 10 additions and 25 deletions

5
app/package-lock.json generated
View File

@ -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",

View File

@ -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",

View File

@ -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 () => {

View File

@ -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;
}