-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathusePredictMarketData.tsx
More file actions
262 lines (236 loc) · 7.66 KB
/
usePredictMarketData.tsx
File metadata and controls
262 lines (236 loc) · 7.66 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* eslint-disable react/prop-types */
import {
useCallback,
useEffect,
useLayoutEffect,
useState,
useRef,
} from 'react';
import Engine from '../../../../core/Engine';
import { DevLogger } from '../../../../core/SDKConnect/utils/DevLogger';
import Logger from '../../../../util/Logger';
import { PREDICT_CONSTANTS } from '../constants/errors';
import { ensureError } from '../utils/predictErrorHandler';
import { PredictCategory, PredictMarket } from '../types';
import { filterStandaloneMarkets } from '../utils/feed';
export interface UsePredictMarketDataOptions {
q?: string;
category?: PredictCategory;
pageSize?: number;
customQueryParams?: string;
refine?: (markets: PredictMarket[]) => PredictMarket[];
/** When false, skips fetches (e.g. Predict feature off while section stays mounted). */
enabled?: boolean;
}
export interface UsePredictMarketDataResult {
marketData: PredictMarket[];
isFetching: boolean;
isFetchingMore: boolean;
error: string | null;
hasMore: boolean;
refetch: () => Promise<void>;
fetchMore: () => Promise<void>;
}
/**
* Hook to fetch and manage market data for a specific category with infinite scroll
* @returns Market data, loading states, and pagination controls
*/
export const usePredictMarketData = (
options: UsePredictMarketDataOptions = {},
): UsePredictMarketDataResult => {
const {
category = 'trending',
q,
pageSize = 20,
customQueryParams,
refine,
enabled = true,
} = options;
const [marketData, setMarketData] = useState<PredictMarket[]>([]);
const [isLoading, setIsLoading] = useState(enabled);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const [error, setError] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(true);
const [currentOffset, setCurrentOffset] = useState(0);
const currentCategoryRef = useRef(category);
const currentOffsetRef = useRef(currentOffset);
const prevEnabledRef = useRef(enabled);
/**
* When `enabled` goes from false → true (e.g. All Sports pill), avoid one painted frame
* with empty data and `isFetching` still false from the disabled path before `useEffect` fetch runs.
*/
useLayoutEffect(() => {
if (enabled && !prevEnabledRef.current) {
setIsLoading(true);
}
prevEnabledRef.current = enabled;
}, [enabled]);
useEffect(() => {
currentCategoryRef.current = category;
}, [category]);
useEffect(() => {
currentOffsetRef.current = currentOffset;
}, [currentOffset]);
const fetchMarketData = useCallback(
async (isLoadMore = false) => {
if (!enabled) {
setIsLoading(false);
setIsLoadingMore(false);
if (!isLoadMore) {
setMarketData([]);
}
return;
}
try {
if (isLoadMore) {
setIsLoadingMore(true);
} else {
setIsLoading(true);
setCurrentOffset(0);
currentOffsetRef.current = 0;
}
setError(null);
const offset = isLoadMore ? currentOffsetRef.current : 0;
DevLogger.log(
'Fetching market data for category:',
category,
'search:',
q,
'offset:',
offset,
'limit:',
pageSize,
);
let retryCount = 0;
const maxRetries = 3;
const baseDelay = 1000;
while (retryCount < maxRetries) {
try {
if (!Engine || !Engine.context) {
throw new Error('Engine not initialized');
}
const controller = Engine.context.PredictController;
if (!controller) {
throw new Error('Predict controller not available');
}
const markets = await controller.getMarkets({
category,
q,
limit: pageSize,
offset,
customQueryParams,
});
DevLogger.log('Market data received:', markets);
if (!markets || !Array.isArray(markets)) {
if (isLoadMore) {
setHasMore(false);
} else {
setMarketData([]);
}
return;
}
const hasMoreData = markets.length >= pageSize;
setHasMore(hasMoreData);
const visibleMarkets = filterStandaloneMarkets(markets);
if (isLoadMore) {
setMarketData((prevData) => {
// Use a Set to efficiently deduplicate by ID
const existingIds = new Set(prevData.map((event) => event.id));
const newEvents = visibleMarkets.filter(
(event) => !existingIds.has(event.id),
);
const accumulated = [...prevData, ...newEvents];
return refine ? refine(accumulated) : accumulated;
});
setCurrentOffset((prev) => prev + pageSize);
currentOffsetRef.current += pageSize;
} else {
// Replace data for initial load or refresh
setMarketData(refine ? refine(visibleMarkets) : visibleMarkets);
setCurrentOffset(pageSize);
currentOffsetRef.current = pageSize;
}
// Success - break out of retry loop
break;
} catch (engineError) {
retryCount++;
if (retryCount >= maxRetries) {
throw engineError;
}
// Exponential backoff with jitter
const delay =
baseDelay * Math.pow(2, retryCount - 1) + Math.random() * 1000;
DevLogger.log(
`Engine not ready, retrying in ${Math.round(
delay,
)}ms (attempt ${retryCount}/${maxRetries})`,
);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
} catch (err) {
DevLogger.log('Error fetching market data:', err);
const errorMessage =
err instanceof Error ? err.message : 'Failed to fetch market data';
setError(errorMessage);
// Capture exception with market data loading context
Logger.error(ensureError(err), {
tags: {
feature: PREDICT_CONSTANTS.FEATURE_NAME,
component: 'usePredictMarketData',
},
context: {
name: 'usePredictMarketData',
data: {
method: 'loadMarketData',
action: 'market_data_load',
operation: 'data_fetching',
category,
hasSearchQuery: !!q,
pageSize,
isLoadMore,
},
},
});
if (!isLoadMore) {
setMarketData([]);
}
} finally {
setIsLoading(false);
setIsLoadingMore(false);
}
},
[category, q, pageSize, customQueryParams, refine, enabled],
);
const loadMore = useCallback(async () => {
if (!enabled || isLoadingMore || !hasMore) return;
await fetchMarketData(true);
}, [enabled, fetchMarketData, isLoadingMore, hasMore]);
const refetch = useCallback(async () => {
if (!enabled) return;
await fetchMarketData(false);
}, [enabled, fetchMarketData]);
// Reset pagination when category or search changes
useEffect(() => {
setCurrentOffset(0);
currentOffsetRef.current = 0;
setHasMore(true);
setMarketData([]);
if (!enabled) {
setIsLoading(false);
setIsLoadingMore(false);
setError(null);
return;
}
fetchMarketData(false);
}, [category, q, customQueryParams, fetchMarketData, enabled]);
return {
marketData,
isFetching: isLoading,
isFetchingMore: isLoadingMore,
error,
hasMore,
refetch,
fetchMore: loadMore,
};
};