-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
general.ts
373 lines (323 loc) · 12.1 KB
/
general.ts
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import type { SerializeFrom } from '@remix-run/node'
import type { FetcherWithComponents, SubmitFunction } from '@remix-run/react'
import { useFetcher } from '@remix-run/react'
import type { AppData } from '@remix-run/react/dist/data'
import { useRef, useEffect, useCallback, useState, useMemo } from 'react'
/// https://github.com/remix-run/remix/discussions/3657
export function useHackedFetcher<T>() {
const originalFetcher = useFetcher<T>()
const fakeMemoizedFetcher = useMemo(() => ({}) as typeof originalFetcher, [])
return Object.assign(fakeMemoizedFetcher, originalFetcher)
}
// Credits: https://gist.github.com/arunmmanoharan/38d313f28dc17637a0e3cfa8c6205bd5
// Contributing users: arunmmanoharan
// May 10 2024
/**
* A higher-order function that creates a new FetcherWithComponentsReset instance, which extends the FetcherWithComponents interface.
* The new instance includes an additional method `reset` that can be used to reset the state of the fetcher.
*
* @template T - The type of data returned by the fetcher.
* @param fetcherWithComponents - The FetcherWithComponents instance to be extended.
* @returns A new FetcherWithComponentsReset instance.
*
*
*
*/
export type FetcherWithComponentsReset<T> = FetcherWithComponents<T> & {
reset: () => void
}
// Credits: https://gist.github.com/arunmmanoharan/38d313f28dc17637a0e3cfa8c6205bd5
// Contributing users: arunmmanoharan
// May 10 2024
/**
* Custom hook that wraps the useFetcher hook with the ability to reset data.
*
* @param {Object} opts - Optional options to pass to the useFetcher hook.
* @returns {Object} - An object containing fetcher properties with added reset functionality.
*/
export function useFetcherWithReset<T = AppData>(
opts?: Parameters<typeof useFetcher>[0],
): FetcherWithComponentsReset<SerializeFrom<T>> {
const fetcher = useFetcher<T>(opts)
const [data, setData] = useState(fetcher.data)
useEffect(() => {
if (fetcher.state === 'idle') {
setData(fetcher.data)
}
}, [fetcher.state, fetcher.data])
return {
...fetcher,
data: data as SerializeFrom<T>,
reset: () => setData(undefined),
}
}
// Properly handle environment variables with a helper function
export const getEnvVar = (key: string, defaultValue?: string): string => {
const value = process.env[key]
if (value !== undefined) return value
if (defaultValue !== undefined) return defaultValue
throw new Error(`Environment variable ${key} is not set`)
}
// Inspiration taken from https://gist.github.com/samselikoff/510c020e4c9ec17f1cf76189ce683fa8
// Contributing users: Samselikoff & jjhiggzw
// April 27 2024
/**
* This type extends FetcherWithComponents to include additional methods for reset and promise-based submissions.
* It encapsulates both state management and asynchronous operations into a single fetcher interface.
* This is ideal for handling complex data fetching and updating scenarios in a React application, particularly within Remix.
*
* @template T - The data type the fetcher is expected to handle.
* @property reset - A method to manually reset the internal state and promise of the fetcher.
*/
export type ExtendedCustomFetcherTemp<T> = FetcherWithComponents<T> & {}
/**
* Custom hook that enhances the useFetcher hook with a promise-based API.
* The useFetcherWithPromise hook wraps the useFetcher hook and provides a promise that resolves when the fetcher's state becomes idle and it has data.
* This allows you to easily handle asynchronous operations and retrieve the data using promises.
*
* @returns An object containing the fetcher state, data, and a submit function.
*/
export function useFetcherWithPromiseAutoReset<T = AppData>(
opts?: Parameters<typeof useFetcher>[0],
): ExtendedCustomFetcherTemp<SerializeFrom<T>> {
let resolveRef = useRef<any>()
let promiseRef = useRef<Promise<any>>()
const fetcher = useFetcher<T>(opts)
const [data, setData] = useState(fetcher.data)
useEffect(() => {
if (fetcher.state === 'idle') {
setData(fetcher.data)
}
}, [fetcher.state, fetcher.data])
if (!promiseRef.current) {
promiseRef.current = new Promise(resolve => {
resolveRef.current = resolve
})
}
// Initialize or reset the promise and its resolver.
const initializePromise = useCallback(() => {
promiseRef.current = new Promise(resolve => {
resolveRef.current = resolve
})
}, [])
// Custom submit function that uses the promise mechanism.
const submit = useCallback(
async (...args: Parameters<SubmitFunction>) => {
await fetcher.submit(...args)
return promiseRef.current // Return the current promise which resolves when the fetcher is idle and has data.
},
[fetcher],
)
useEffect(() => {
if (fetcher.state === 'idle' && fetcher.data) {
resolveRef.current(fetcher.data)
initializePromise() // Reset the promise after handling to prepare for next operation
}
}, [fetcher.data, fetcher.state, initializePromise])
return {
...fetcher,
data: data as SerializeFrom<T>,
submit,
}
}
/**
* This type extends FetcherWithComponents to include additional methods for reset and promise-based submissions.
* It encapsulates both state management and asynchronous operations into a single fetcher interface.
* This is ideal for handling complex data fetching and updating scenarios in a React application, particularly within Remix.
*
* @template T - The data type the fetcher is expected to handle.
* @property reset - A method to manually reset the internal state and promise of the fetcher.
*/
export type ExtendedCustomFetcher<T> = FetcherWithComponents<T> & {
reset: () => void
}
export function useFetcherWithPromiseAndResetStable<T = AppData>(
opts?: Parameters<typeof useFetcher>[0],
): ExtendedCustomFetcher<SerializeFrom<T>> {
const fetcher = useFetcher<T>(opts)
const promiseResolverRef = useRef<(value: SerializeFrom<T>) => void>()
const fetcherPromiseRef = useRef<Promise<SerializeFrom<T>>>()
// Initialize or reset the promise and its resolver.
const initializePromise = useCallback(() => {
fetcherPromiseRef.current = new Promise(resolve => {
promiseResolverRef.current = resolve
})
}, [])
// Manual reset function to reinitialize the promise, allowing the fetcher to be reused after completion.
const reset = useCallback(() => {
initializePromise()
}, [initializePromise])
// Custom submit function that uses the promise mechanism.
const submit = useCallback(
async (...args: Parameters<SubmitFunction>) => {
fetcher.submit(...args)
return fetcherPromiseRef.current // Return the current promise which resolves when the fetcher is idle and has data.
},
[fetcher],
)
useEffect(() => {
initializePromise()
}, [initializePromise])
return {
...fetcher,
submit,
reset,
}
}
/**
* A custom hook that combines the functionality of the standard Remix useFetcher hook with the ability to manually reset its state
* and manage submissions through promises. This allows components to initiate fetch operations and rely on promises to handle
* subsequent updates or effects based on the fetch state and data.
*
* Imperfect and Company
* May 10, 2024
* Inspiration from arunmmanoharan, Samselikoff, jjhiggzw
*
* @param {Object} opts - Optional configurations for useFetcher, such as `key` to maintain identity in React's reconciliation.
* @returns {ExtendedCustomFetcher} - An enhanced fetcher that supports manual resetting state and promise-based submissions.
*/
export function useFetcherWithPromiseAndReset<T = AppData>(
opts?: Parameters<typeof useFetcher>[0],
): ExtendedCustomFetcher<SerializeFrom<T>> {
const fetcher = useFetcher<T>(opts)
const promiseResolverRef = useRef<(value: SerializeFrom<T>) => void>()
const fetcherPromiseRef = useRef<Promise<SerializeFrom<T>>>()
// Initialize or reset the promise and its resolver.
const initializePromise = useCallback(() => {
fetcherPromiseRef.current = new Promise(resolve => {
promiseResolverRef.current = resolve
})
}, [])
// Manual reset function to reinitialize the promise, allowing the fetcher to be reused after completion.
const reset = useCallback(() => {
initializePromise()
}, [initializePromise])
// Custom submit function that uses the promise mechanism.
const submit = useCallback(
async (...args: Parameters<SubmitFunction>) => {
fetcher.submit(...args)
return fetcherPromiseRef.current // Return the current promise which resolves when the fetcher is idle and has data.
},
[fetcher],
)
// Return back to updating with this later -- not priority.
// useEffect(() => {
// if (fetcher.state === 'idle' && fetcher.data && promiseResolverRef.current) {
// promiseResolverRef.current(fetcher.data);
// initializePromise(); // Reset the promise after handling to prepare for next operation
// }
// }, [fetcher.data, fetcher.state, initializePromise]);
useEffect(() => {
initializePromise()
}, [initializePromise])
return {
...fetcher,
submit,
reset,
}
}
// Inspiration taken from https://gist.github.com/samselikoff/510c020e4c9ec17f1cf76189ce683fa8
// Contributing users: Samselikoff & jjhiggzw
// April 27 2024
/**
*
* @returns An object containing the fetcher state, data, manual reset, and a submit function.
*/
export function useFetcherWithPromiseAndManualReset<T = AppData>(
opts?: Parameters<typeof useFetcher>[0],
): FetcherWithComponentsReset<SerializeFrom<T>> {
let resolveRef = useRef<any>()
let promiseRef = useRef<Promise<any>>()
const fetcher = useFetcher<T>(opts)
if (!promiseRef.current) {
promiseRef.current = new Promise(resolve => {
resolveRef.current = resolve
})
}
// Initialize or reset the promise and its resolver.
const resetResolver = useCallback(() => {
promiseRef.current = new Promise(resolve => {
resolveRef.current = resolve
})
}, [promiseRef, resolveRef])
// Manual reset function to reinitialize the promise, allowing the fetcher to be reused after completion.
const reset = useCallback(() => {
if (fetcher.state === 'idle' && fetcher.data) {
resetResolver()
}
}, [fetcher.data, fetcher.state, resetResolver])
const submit = useCallback(
async (...args: Parameters<SubmitFunction>) => {
fetcher.submit(...args)
return promiseRef.current
},
[fetcher, promiseRef],
)
return {
...fetcher,
submit,
reset,
}
}
// export function useFetcherWithPromise<T = AppData>(
// opts?: Parameters<typeof useFetcher>[0],
// ): FetcherWithComponentsReset<SerializeFrom<T>> {
// let resolveRef = useRef<any>()
// let promiseRef = useRef<Promise<any>>()
// const fetcher = useFetcher<T>(opts);
// if (!promiseRef.current) {
// promiseRef.current = new Promise(resolve => {
// resolveRef.current = resolve
// })
// }
// const submit = useCallback(
// async (...args: Parameters<SubmitFunction>) => {
// fetcher.submit(...args)
// return promiseRef.current
// },
// [fetcher, promiseRef],
// )
// return {
// ...fetcher,
// submit,
// };
// }
// Inspiration taken from https://gist.github.com/samselikoff/510c020e4c9ec17f1cf76189ce683fa8
// Contributing users: Samselikoff & jjhiggzw
// April 27 2024
/**
* Custom hook that enhances the useFetcher hook with a promise-based API.
* The useFetcherWithPromise hook wraps the useFetcher hook and provides a promise that resolves when the fetcher's state becomes idle and it has data.
* This allows you to easily handle asynchronous operations and retrieve the data using promises.
*
* @returns An object containing the fetcher state, data, and a submit function.
*/
export function useFetcherWithPromise() {
let resolveRef = useRef<any>()
let promiseRef = useRef<Promise<any>>()
let fetcher = useFetcher()
if (!promiseRef.current) {
promiseRef.current = new Promise(resolve => {
resolveRef.current = resolve
})
}
const resetResolver = useCallback(() => {
promiseRef.current = new Promise(resolve => {
resolveRef.current = resolve
})
}, [promiseRef, resolveRef])
const submit = useCallback(
async (...args: Parameters<SubmitFunction>) => {
fetcher.submit(...args)
return promiseRef.current
},
[fetcher, promiseRef],
)
useEffect(() => {
if (fetcher.state === 'idle' && fetcher.data) {
resolveRef.current(fetcher.data)
resetResolver() // Reset the promise after handling to prepare for next operation
}
}, [fetcher.data, fetcher.state, resetResolver])
return { ...fetcher, submit }
}