From 79f3348986327b1fc1558c02c618425c997e04f2 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Wed, 6 Oct 2021 10:27:16 +0100 Subject: [PATCH] Simplify and improve useRoomHierarchy hook --- src/components/structures/SpaceHierarchy.tsx | 25 ++++++-------------- 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/src/components/structures/SpaceHierarchy.tsx b/src/components/structures/SpaceHierarchy.tsx index ed87b04c8a..069454f842 100644 --- a/src/components/structures/SpaceHierarchy.tsx +++ b/src/components/structures/SpaceHierarchy.tsx @@ -410,50 +410,39 @@ export const HierarchyLevel = ({ const INITIAL_PAGE_SIZE = 20; -export const useSpaceSummary = (space: Room): { +export const useRoomHierarchy = (space: Room): { loading: boolean; rooms: IHierarchyRoom[]; hierarchy: RoomHierarchy; loadMore(pageSize?: number): Promise ; } => { const [rooms, setRooms] = useState([]); - const [loading, setLoading] = useState(true); const [hierarchy, setHierarchy] = useState(); const resetHierarchy = useCallback(() => { const hierarchy = new RoomHierarchy(space, INITIAL_PAGE_SIZE); - setHierarchy(hierarchy); - - let discard = false; hierarchy.load().then(() => { - if (discard) return; + if (space !== hierarchy.root) return; // discard stale results setRooms(hierarchy.rooms); - setLoading(false); }); - - return () => { - discard = true; - }; + setHierarchy(hierarchy); }, [space]); useEffect(resetHierarchy, [resetHierarchy]); useDispatcher(defaultDispatcher, (payload => { if (payload.action === Action.UpdateSpaceHierarchy) { - setLoading(true); setRooms([]); // TODO resetHierarchy(); } })); const loadMore = useCallback(async (pageSize?: number) => { - if (loading || !hierarchy.canLoadMore || hierarchy.noSupport) return; - - setLoading(true); + if (hierarchy.loading || !hierarchy.canLoadMore || hierarchy.noSupport) return; await hierarchy.load(pageSize); setRooms(hierarchy.rooms); - setLoading(false); - }, [loading, hierarchy]); + }, [hierarchy]); + const loading = hierarchy?.loading ?? true; return { loading, rooms, hierarchy, loadMore }; }; @@ -587,7 +576,7 @@ const SpaceHierarchy = ({ const [selected, setSelected] = useState(new Map>()); // Map> - const { loading, rooms, hierarchy, loadMore } = useSpaceSummary(space); + const { loading, rooms, hierarchy, loadMore } = useRoomHierarchy(space); const filteredRoomSet = useMemo>(() => { if (!rooms?.length) return new Set();