Skip to content

Commit

Permalink
Merge pull request #1868 from ever-co/fix/#1867-api-performance-impro…
Browse files Browse the repository at this point in the history
…vement

fix: #1867 Improved API performance issue for timer status API
  • Loading branch information
evereq authored Nov 24, 2023
2 parents 3d744c1 + a0d17b9 commit 36e1ae4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
7 changes: 5 additions & 2 deletions apps/web/app/hooks/features/useTimer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export function useTimer() {
const { firstLoad, firstLoadData: firstLoadTimerData } = useFirstLoad();

// Queries
const { queryCall, loading } = useQuery(getTimerStatusAPI);
const { queryCall, loading, loadingRef } = useQuery(getTimerStatusAPI);
const { queryCall: toggleQueryCall } = useQuery(toggleTimerAPI);
const { queryCall: startTimerQueryCall } = useQuery(startTimerAPI);
const { queryCall: stopTimerQueryCall, loading: stopTimerLoading } = useQuery(stopTimerAPI);
Expand All @@ -187,6 +187,9 @@ export function useTimer() {

const getTimerStatus = useCallback(
(deepCheck?: boolean) => {
if (loadingRef.current) {
return;
}
return queryCall().then((res) => {
if (res.data && !isEqual(timerStatus, res.data)) {
setTimerStatus((t) => {
Expand All @@ -199,7 +202,7 @@ export function useTimer() {
return res;
});
},
[timerStatus, setTimerStatus, queryCall]
[timerStatus, setTimerStatus, queryCall, loadingRef]
);

const toggleTimer = useCallback(
Expand Down
11 changes: 9 additions & 2 deletions apps/web/app/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,28 @@ import { useCallback, useRef, useState } from 'react';

export function useQuery<T extends (...params: any[]) => Promise<any>>(queryFunction: T) {
const [loading, setLoading] = useState(false);
const loadingRef = useRef(false);
const infiniteLoading = useRef(false);

const queryCall = useCallback((...params: Parameters<T>) => {
setLoading(true);
loadingRef.current = true;

const promise = queryFunction(...params);
promise.finally(() => {
!infiniteLoading.current && setLoading(false);
if (!infiniteLoading.current) {
setLoading(false);

loadingRef.current = false;
}
});
promise.catch(() => {
setLoading(false);
loadingRef.current = false;
});
return promise;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []) as T;

return { queryCall, loading, infiniteLoading };
return { queryCall, loading, infiniteLoading, loadingRef };
}

0 comments on commit 36e1ae4

Please sign in to comment.