From f7a1680f72fdc5e692b64826c4dfeee23a945044 Mon Sep 17 00:00:00 2001 From: CorrectRoadH Date: Sat, 29 Apr 2023 00:17:08 +0800 Subject: [PATCH] fix: only delete last file when select multiple files #1576 (#1578) * fix the bug can't delete multiple files #1576 * using useEvent instead of useRef * delete unused code * delete unused code * change hook file name * refactor the useEvent * delete unnecessary export * fix import * Apply suggestions from code review --------- Co-authored-by: boojack --- web/src/hooks/useEvent.ts | 25 +++++++++++++++++++++++++ web/src/pages/ResourcesDashboard.tsx | 9 +++++---- 2 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 web/src/hooks/useEvent.ts diff --git a/web/src/hooks/useEvent.ts b/web/src/hooks/useEvent.ts new file mode 100644 index 00000000..8b218d47 --- /dev/null +++ b/web/src/hooks/useEvent.ts @@ -0,0 +1,25 @@ +import React, { useEffect, useRef, EffectCallback, DependencyList } from "react"; + +const useIsoMorphicEffect = (effect: EffectCallback, deps?: DependencyList | undefined) => { + useEffect(effect, deps); +}; + +function useLatestValue(value: T) { + const cache = useRef(value); + + useIsoMorphicEffect(() => { + cache.current = value; + }, [value]); + + return cache; +} + +// TODO: Add React.useEvent ?? once the useEvent hook is available +function useEvent any, P extends any[] = Parameters, R = ReturnType>( + cb: (...args: P) => R +) { + const cache = useLatestValue(cb); + return React.useCallback((...args: P) => cache.current(...args), [cache]); +}; + +export default useEvent; diff --git a/web/src/pages/ResourcesDashboard.tsx b/web/src/pages/ResourcesDashboard.tsx index b230c58e..dff5cf18 100644 --- a/web/src/pages/ResourcesDashboard.tsx +++ b/web/src/pages/ResourcesDashboard.tsx @@ -13,6 +13,7 @@ import Dropdown from "@/components/kit/Dropdown"; import ResourceItem from "@/components/ResourceItem"; import { showCommonDialog } from "@/components/Dialog/CommonDialog"; import showCreateResourceDialog from "@/components/CreateResourceDialog"; +import useEvent from "@/hooks/useEvent"; const ResourcesDashboard = () => { const { t } = useTranslation(); @@ -40,13 +41,13 @@ const ResourcesDashboard = () => { }); }, []); - const handleCheckBtnClick = (resourceId: ResourceId) => { + const handleCheckBtnClick = useEvent((resourceId: ResourceId) => { setSelectedList([...selectedList, resourceId]); - }; + }); - const handleUncheckBtnClick = (resourceId: ResourceId) => { + const handleUncheckBtnClick = useEvent((resourceId: ResourceId) => { setSelectedList(selectedList.filter((id) => id !== resourceId)); - }; + }); const handleStyleChangeBtnClick = (listStyle: "GRID" | "TABLE") => { setListStyle(listStyle);