From 2e371645939a4d25762872788aed65fba710f5c3 Mon Sep 17 00:00:00 2001 From: Wieslaw Date: Sun, 15 Dec 2024 02:14:35 +0100 Subject: [PATCH] client: Fix race condition in InfiniteScroll --- client/src/api/managment-service.ts | 9 +++------ client/src/hooks/useInfiniteScroll.tsx | 15 +++++++++++---- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/client/src/api/managment-service.ts b/client/src/api/managment-service.ts index 79b72ca0..ec3685f2 100644 --- a/client/src/api/managment-service.ts +++ b/client/src/api/managment-service.ts @@ -478,6 +478,7 @@ class ManagmentServiceApi { // eslint-disable-next-line `/api/v1/reports/application-incidents/${incidentId}/sources?page=${page}&size=${size}&sort=timestamp`, ); + return report.data; } @@ -512,13 +513,9 @@ class ManagmentServiceApi { return response.data; } - public async getLatestReport(): Promise< - ReportDetails - > { + public async getLatestReport(): Promise { await this.refreshTokenIfExpired(); - const response = await this.axiosInstance.get( - '/api/v1/reports/latest', - ); + const response = await this.axiosInstance.get('/api/v1/reports/latest'); return response.data; } diff --git a/client/src/hooks/useInfiniteScroll.tsx b/client/src/hooks/useInfiniteScroll.tsx index 385b3f03..74010e6c 100644 --- a/client/src/hooks/useInfiniteScroll.tsx +++ b/client/src/hooks/useInfiniteScroll.tsx @@ -1,11 +1,11 @@ import { debounce } from 'lib/debounce'; -import { useEffect } from 'react'; +import { useEffect, useState } from 'react'; interface UseInfiniteScrollParams { scrollTargetRef: React.RefObject; debounceTreshhold?: number; scrollTreshhold?: number; - handleScroll: () => void; + handleScroll: () => Promise | void; } const useInfiniteScroll = ({ @@ -14,18 +14,25 @@ const useInfiniteScroll = ({ scrollTreshhold = 2, handleScroll, }: UseInfiniteScrollParams) => { + const [isHandling, setIsHandling] = useState(false); useEffect(() => { - const onScroll = () => { + const onScroll = async () => { const element = scrollTargetRef.current; if (!element) { return; } + if (isHandling === true) { + return; + } + if ( element.scrollTop + element.clientHeight >= element.scrollHeight / scrollTreshhold ) { - handleScroll(); + setIsHandling(true); + await handleScroll(); + setIsHandling(false); } };