-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseGeoQuery.tsx
117 lines (115 loc) · 2.89 KB
/
useGeoQuery.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { RequestForQueries, useQueries } from "convex/react";
import { useState, useMemo, useEffect } from "react";
import { Rectangle } from "@convex-dev/geospatial";
import { api } from "../convex/_generated/api";
import { FunctionReturnType } from "convex/server";
type Rows = FunctionReturnType<typeof api.example.search>["rows"];
export function useGeoQuery(
rectangle: Rectangle,
mustFilter: string[],
shouldFilter: string[],
maxRows: number,
) {
const [queries, setQueries] = useState<RequestForQueries>({});
const argsKey = useMemo(
() =>
JSON.stringify({
rectangle,
mustFilter,
shouldFilter,
}),
[rectangle, mustFilter, shouldFilter],
);
const queryResults = useQueries(queries);
useEffect(() => {
const startKey = `${argsKey}@0`;
if (queries[startKey] === undefined) {
setQueries({
[startKey]: {
query: api.example.search,
args: {
rectangle,
mustFilter,
shouldFilter,
maxRows,
},
},
});
return;
}
let lastResult = queryResults[startKey];
if (lastResult instanceof Error) {
throw lastResult;
}
if (!lastResult) {
return;
}
if (!lastResult.nextCursor) {
return;
}
let totalRows = lastResult.rows.length;
for (let i = 1; ; i++) {
if (totalRows >= maxRows) {
break;
}
const key = `${argsKey}@${i}`;
if (queries[key] === undefined) {
setQueries({
...queries,
[key]: {
query: api.example.search,
args: {
rectangle,
mustFilter,
shouldFilter,
maxRows: maxRows - totalRows,
cursor: lastResult.nextCursor,
},
},
});
break;
}
const result = queryResults[key];
if (result === undefined) {
break;
}
if (result instanceof Error) {
throw result;
}
if (!result.nextCursor) {
break;
}
lastResult = result;
totalRows += result.rows.length;
}
}, [queries, argsKey, queryResults]);
const rows: Rows = [];
const seen = new Set<string>();
let loading = false;
let foundAny = false;
for (const [key, result] of Object.entries(queryResults)) {
if (key.startsWith(argsKey)) {
foundAny = true;
if (result instanceof Error) {
throw result;
}
if (result) {
for (const row of result.rows) {
// Since we don't have proper reactive pagination yet with stable
// boundaries, just deduplicate results if pages overlap.
if (seen.has(row._id)) {
continue;
}
rows.push(row);
seen.add(row._id);
}
} else {
loading = true;
}
}
}
if (!foundAny) {
loading = true;
}
return { rows, loading };
}