Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add concurrent requests limit #35

Merged
merged 1 commit into from
Jul 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 45 additions & 20 deletions hooks/useRequest.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { useState, useEffect, useContext, useCallback } from 'react';
import { DataContext } from '../contexts/data';

let runningRequests: number = 0;
const MAX_CONCURRENT_REQUESTS = 4;

const fetcher = (url: string) => fetch(url).then((res) => res.json());

export function useRequest(url: string, defaultValue: any, key?: string, dontRefetch?: boolean) {
Expand All @@ -9,26 +12,48 @@ export function useRequest(url: string, defaultValue: any, key?: string, dontRef
const dataContext = useContext(DataContext);

const init = useCallback(async () => {
setLoading(true);
const data = await fetcher(`${process.env.NEXT_PUBLIC_DAT_URL}/${url}`);
const dataFromKey = key ? data[key] : data?.table_data || data?.chart_data || data;
setData(
dataFromKey.filter
? dataFromKey.filter((line: any) => {
if (!line.time) {
return true;
}
if (dataContext.dates.from && new Date(line.time) < new Date(dataContext.dates.from)) {
return false;
}
if (dataContext.dates.to && new Date(line.time) > new Date(dataContext.dates.to)) {
return false;
}
return true;
})
: dataFromKey
);
setLoading(false);
const request = async () => {
if (runningRequests > MAX_CONCURRENT_REQUESTS) {
setTimeout(() => {
request();
}, 500);
return;
}

runningRequests++;
setLoading(true);
try {
const data = await fetcher(`${process.env.NEXT_PUBLIC_DAT_URL}/${url}`);
runningRequests--;

const dataFromKey = key ? data[key] : data?.table_data || data?.chart_data || data;
setData(
dataFromKey.filter
? dataFromKey.filter((line: any) => {
if (!line.time) {
return true;
}
if (
dataContext.dates.from &&
new Date(line.time) < new Date(dataContext.dates.from)
) {
return false;
}
if (dataContext.dates.to && new Date(line.time) > new Date(dataContext.dates.to)) {
return false;
}
return true;
})
: dataFromKey
);
setLoading(false);
} catch (e) {
console.log(e);
runningRequests--;
}
};

request();
}, [dataContext.dates.from, dataContext.dates.to, key, url]);

useEffect(() => {
Expand Down