Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

make searchWorker setFiles useEffect SingleThreaded

Abhinav49c4331f8106
diff --git a/apps/photos/src/pages/gallery/index.tsx b/apps/photos/src/pages/gallery/index.tsx
index ba55929265..c2dadc0b34 100644
--- a/apps/photos/src/pages/gallery/index.tsx
+++ b/apps/photos/src/pages/gallery/index.tsx
@@ -132,6 +132,7 @@ import downloadManager from 'services/download';
import { APPS } from '@ente/shared/apps/constants';
import locationSearchService from 'services/locationSearchService';
import ComlinkSearchWorker from 'utils/comlink/ComlinkSearchWorker';
+import useEffectSingleThreaded from '@ente/shared/hooks/useEffectSingleThreaded';
export const DeadCenter = styled('div')`
flex: 1;
@@ -363,13 +364,13 @@ export default function Gallery() {
};
}, []);
- useEffect(() => {
- const main = async () => {
+ useEffectSingleThreaded(
+ async ([files]: [files: EnteFile[]]) => {
const searchWorker = await ComlinkSearchWorker.getInstance();
- searchWorker.setFiles(files);
- };
- main();
- }, [files]);
+ await searchWorker.setFiles(files);
+ },
+ [files]
+ );
useEffect(() => {
if (!user || !files || !collections || !hiddenFiles || !trashedFiles) {
diff --git a/packages/shared/hooks/useEffectSingleThreaded.tsx b/packages/shared/hooks/useEffectSingleThreaded.tsx
new file mode 100644
index 0000000000..94f4f1931d
--- /dev/null
+++ b/packages/shared/hooks/useEffectSingleThreaded.tsx
@@ -0,0 +1,30 @@
+import { useEffect, useRef } from 'react';
+import { isPromise } from '../utils';
+
+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);
+}
diff --git a/packages/shared/utils/index.ts b/packages/shared/utils/index.ts
index f839377020..d65ef43800 100644
--- a/packages/shared/utils/index.ts
+++ b/packages/shared/utils/index.ts
@@ -22,3 +22,7 @@ export function downloadUsingAnchor(link: string, name: string) {
URL.revokeObjectURL(link);
a.remove();
}
+
+export function isPromise<T>(obj: T | Promise<T>): obj is Promise<T> {
+ return obj && typeof (obj as any).then === 'function';
+}