This commit is contained in:
Manav Rathi 2024-04-05 20:03:23 +05:30
parent 461430a972
commit 7807d3a413
No known key found for this signature in database
2 changed files with 32 additions and 34 deletions

View file

@ -92,13 +92,13 @@ import {
import { APPS } from "@ente/shared/apps/constants";
import { CenteredFlex } from "@ente/shared/components/Container";
import ElectronAPIs from "@ente/shared/electron";
import useEffectSingleThreaded from "@ente/shared/hooks/useEffectSingleThreaded";
import useFileInput from "@ente/shared/hooks/useFileInput";
import useMemoSingleThreaded from "@ente/shared/hooks/useMemoSingleThreaded";
import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
import { getToken } from "@ente/shared/storage/localStorage/helpers";
import { User } from "@ente/shared/user/types";
import { isPromise } from "@ente/shared/utils";
import AuthenticateUserModal from "components/AuthenticateUserModal";
import Collections from "components/Collections";
import ExportModal from "components/ExportModal";
@ -1221,3 +1221,34 @@ export default function Gallery() {
</GalleryContext.Provider>
);
}
// useEffectSingleThreaded is a useEffect that will only run one at a time, and will
// caches the latest deps of requests that come in while it is running, and will
// run that after the current run is complete.
function useEffectSingleThreaded(
fn: (deps) => void | Promise<void>,
deps: any[],
): void {
const updateInProgress = useRef(false);
const nextRequestDepsRef = useRef<any[]>(null);
useEffect(() => {
const main = async (deps) => {
if (updateInProgress.current) {
nextRequestDepsRef.current = deps;
return;
}
updateInProgress.current = true;
const result = fn(deps);
if (isPromise(result)) {
await result;
}
updateInProgress.current = false;
if (nextRequestDepsRef.current) {
const deps = nextRequestDepsRef.current;
nextRequestDepsRef.current = null;
setTimeout(() => main(deps), 0);
}
};
main(deps);
}, deps);
}

View file

@ -1,33 +0,0 @@
import { useEffect, useRef } from "react";
import { isPromise } from "../utils";
// useEffectSingleThreaded is a useEffect that will only run one at a time, and will
// caches the latest deps of requests that come in while it is running, and will
// run that after the current run is complete.
export default function useEffectSingleThreaded(
fn: (deps) => void | Promise<void>,
deps: any[],
): void {
const updateInProgress = useRef(false);
const nextRequestDepsRef = useRef<any[]>(null);
useEffect(() => {
const main = async (deps) => {
if (updateInProgress.current) {
nextRequestDepsRef.current = deps;
return;
}
updateInProgress.current = true;
const result = fn(deps);
if (isPromise(result)) {
await result;
}
updateInProgress.current = false;
if (nextRequestDepsRef.current) {
const deps = nextRequestDepsRef.current;
nextRequestDepsRef.current = null;
setTimeout(() => main(deps), 0);
}
};
main(deps);
}, deps);
}