@ventlio/tanstack-query 0.2.6 → 0.2.7-2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +532 -2
  3. package/dist/config/bootstrapQueryRequest.d.ts +4 -0
  4. package/dist/config/bootstrapQueryRequest.js +19 -0
  5. package/dist/config/bootstrapQueryRequest.js.map +1 -0
  6. package/dist/config/config.interface.d.ts +4 -0
  7. package/dist/config/index.d.ts +4 -2
  8. package/dist/config/useEnvironmentVariables.d.ts +2 -0
  9. package/dist/config/useEnvironmentVariables.js +14 -0
  10. package/dist/config/useEnvironmentVariables.js.map +1 -0
  11. package/dist/config/useQueryConfig.js +5 -9
  12. package/dist/config/useQueryConfig.js.map +1 -1
  13. package/dist/config/useQueryHeaders.js +19 -10
  14. package/dist/config/useQueryHeaders.js.map +1 -1
  15. package/dist/config/useReactNativeEnv.d.ts +5 -0
  16. package/dist/config/useReactNativeEnv.js +13 -0
  17. package/dist/config/useReactNativeEnv.js.map +1 -0
  18. package/dist/helpers/index.d.ts +1 -0
  19. package/dist/helpers/scrollToTop.js +1 -3
  20. package/dist/helpers/scrollToTop.js.map +1 -1
  21. package/dist/helpers/timeFuncs.d.ts +1 -0
  22. package/dist/helpers/timeFuncs.js +11 -0
  23. package/dist/helpers/timeFuncs.js.map +1 -0
  24. package/dist/index.js +19 -43
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +417 -143
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/model/index.d.ts +3 -0
  29. package/dist/model/model.interface.d.ts +11 -0
  30. package/dist/model/useKeyTrackerModel.d.ts +4 -0
  31. package/dist/model/useKeyTrackerModel.js +20 -0
  32. package/dist/model/useKeyTrackerModel.js.map +1 -0
  33. package/dist/model/useQueryModel.d.ts +2 -2
  34. package/dist/model/useQueryModel.js +119 -7
  35. package/dist/model/useQueryModel.js.map +1 -1
  36. package/dist/model/useRefetchQuery.d.ts +3 -0
  37. package/dist/model/useRefetchQuery.js +16 -0
  38. package/dist/model/useRefetchQuery.js.map +1 -0
  39. package/dist/queries/queries.interface.d.ts +5 -0
  40. package/dist/queries/useDeleteRequest.d.ts +14 -5
  41. package/dist/queries/useDeleteRequest.js +37 -37
  42. package/dist/queries/useGetRequest.d.ts +4 -3
  43. package/dist/queries/useGetRequest.js +53 -37
  44. package/dist/queries/useGetRequest.js.map +1 -1
  45. package/dist/queries/usePatchRequest.d.ts +7 -7
  46. package/dist/queries/usePatchRequest.js +42 -34
  47. package/dist/queries/usePatchRequest.js.map +1 -1
  48. package/dist/queries/usePostRequest.d.ts +8 -6
  49. package/dist/queries/usePostRequest.js +47 -37
  50. package/dist/queries/usePostRequest.js.map +1 -1
  51. package/dist/request/axios-instance.d.ts +1 -1
  52. package/dist/request/axios-instance.js +3 -5
  53. package/dist/request/axios-instance.js.map +1 -1
  54. package/dist/request/buildFormData.d.ts +1 -1
  55. package/dist/request/buildFormData.js +36 -6
  56. package/dist/request/buildFormData.js.map +1 -1
  57. package/dist/request/make-request.d.ts +1 -1
  58. package/dist/request/make-request.js +55 -17
  59. package/dist/request/make-request.js.map +1 -1
  60. package/dist/request/request.enum.js +6 -6
  61. package/dist/request/request.interface.d.ts +5 -0
  62. package/dist/request/transformer.js +1 -4
  63. package/dist/request/transformer.js.map +1 -1
  64. package/dist/types/index.d.ts +14 -11
  65. package/package.json +29 -5
  66. package/src/__tests__/queries/usePostRequest.spec.ts +77 -0
  67. package/src/config/bootstrapQueryRequest.ts +19 -0
  68. package/src/config/config.interface.ts +4 -0
  69. package/src/config/index.ts +4 -2
  70. package/src/config/useEnvironmentVariables.ts +13 -0
  71. package/src/config/useQueryConfig.ts +2 -5
  72. package/src/config/useQueryHeaders.ts +23 -6
  73. package/src/config/useReactNativeEnv.ts +13 -0
  74. package/src/env.d.ts +4 -0
  75. package/src/helpers/index.ts +1 -0
  76. package/src/helpers/timeFuncs.ts +10 -0
  77. package/src/model/index.ts +3 -0
  78. package/src/model/model.interface.ts +12 -0
  79. package/src/model/useKeyTrackerModel.ts +22 -0
  80. package/src/model/useQueryModel.ts +139 -6
  81. package/src/model/useRefetchQuery.ts +19 -0
  82. package/src/queries/queries.interface.ts +6 -0
  83. package/src/queries/useDeleteRequest.ts +34 -30
  84. package/src/queries/useGetRequest.ts +55 -38
  85. package/src/queries/usePatchRequest.ts +45 -40
  86. package/src/queries/usePostRequest.ts +54 -37
  87. package/src/request/axios-instance.ts +1 -5
  88. package/src/request/buildFormData.ts +34 -4
  89. package/src/request/make-request.ts +47 -7
  90. package/src/request/request.interface.ts +5 -0
  91. package/src/request/transformer.ts +3 -12
  92. package/src/types/index.ts +16 -13
  93. package/dist/config/useQueryBaseURL.d.ts +0 -2
  94. package/dist/config/useQueryBaseURL.js +0 -19
  95. package/dist/config/useQueryBaseURL.js.map +0 -1
  96. package/dist/config/useQueryTimeout.d.ts +0 -2
  97. package/dist/config/useQueryTimeout.js +0 -19
  98. package/dist/config/useQueryTimeout.js.map +0 -1
  99. package/src/config/useQueryBaseURL.ts +0 -17
  100. package/src/config/useQueryTimeout.ts +0 -17
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present Somtochukwu Okechukwu Stanley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,533 @@
1
- # Ventlio/TanstackQuery
1
+ ### This is a complementary library that should be used with @tanstack/react-query for API REQUESTS and more
2
2
 
3
- ## _Work on progress, we are building an HTTP request handler that uses tanstack-query_
3
+ ## WHY THIS PACKAGE?
4
+
5
+ We have been working on a project using ReactJS and React-Native and we were happy with the React-Query package, now known as Tanstack-Query, which had made our lives easier by managing most of the state management features needed for enterprise software development. This had helped us focus on building functionalities easily without worrying about server state management.
6
+
7
+ However, we still faced some challenges. For each project, we have to configure how Tanstack-Query would connect to the Backend API and manage GET, POST, PUT, and PATCH requests efficiently. One of the major challenges was handling dynamic queryKeys in Tanstack-Query. For example, when building a screen with pagination, useQuery will have re-call the queryFunction every time the key changed, which will load the current page data. This meant that the queryKey changed dynamically, and sometimes we needed to use the queryKey of the current page to perform certain tasks like updating a specific row in the view. This was always tedious.
8
+
9
+ But we were not discouraged. So, we set out to find a solution which led to the development of this package. This package would handle dynamic queryKeys in Tanstack-Query and solve other related problems. It made configuring Tanstack-Query to connect to the Backend API and managing GET, POST, PUT, and PATCH requests a breeze. It also solved the problem of dynamic queryKeys, making it much easier to update specific rows in the view.
10
+
11
+ ---
12
+
13
+ > Please note that this package is still being developed and may not function as expected. We are working to refine its implementation structure to meet a functional standard. The documentation may not align with the current implementation, so if you encounter any difficulties while setting up the package, please raise an issue in the GitHub repository. We appreciate your patience and understanding as we work to improve this package.
14
+
15
+ ### Financial Tasks
16
+
17
+ - [✅] Global settings for requests
18
+ - [✅] Requests context implementations
19
+ - [✅] Post, Get, Patch Requests
20
+ - [Not Completed] Persistent queries implementation
21
+ - [❌] Put request
22
+ - [❌] Generic return type (this is currently an issue if the API does not return object with the necessary properties required by the library)
23
+ - [❌] Server sent events
24
+ - [❌] Socket implementations
25
+ - [❌] Tests
26
+
27
+ ## Installation
28
+
29
+ > You must install @tanstack/react-query and axios first to use this package
30
+
31
+ ```
32
+ yarn add @tanstack/react-query axios
33
+ ```
34
+
35
+ After that install this package
36
+
37
+ ```
38
+ $ npm install @ventlio/tanstack-query
39
+ ```
40
+
41
+ OR
42
+
43
+ ```
44
+ $ yarn add @ventlio/tanstack-query
45
+ ```
46
+
47
+ ## CURRENT RETURN TYPE
48
+
49
+ Currently the library return type expects data structure of the below schema, so depending on the API design,
50
+ you can reach out to the developer to implement the return type that follows the below schema.
51
+
52
+ ```js
53
+ export interface IRequestError {
54
+ statusCode: number;
55
+ message: string;
56
+ timeStamp: Date;
57
+ status: boolean;
58
+ data?: any;
59
+ }
60
+
61
+ export interface IRequestSuccess<T> {
62
+ statusCode: number;
63
+ message: string;
64
+ timeStamp: Date;
65
+ status: boolean;
66
+ data: T;
67
+ }
68
+ ```
69
+
70
+ ## Getting Started
71
+
72
+ Follow the below instructions to have the package running on your project
73
+
74
+ ### Set the environment variables
75
+
76
+ ```env
77
+ # For ReactJS
78
+ REACT_APP_API_URL='https://api.example.com'
79
+ REACT_APP_API_TIMEOUT=300000
80
+
81
+ # For NextJS
82
+ NEXT_PUBLIC_API_URL='https://api.example.com'
83
+ NEXT_PUBLIC_API_TIMEOUT=300000
84
+
85
+ ```
86
+
87
+ ```js
88
+ import { QueryClient } from '@tanstack/react-query';
89
+ import { TanstackQueryConfig, bootstrapQueryRequest } from '@ventlio/tanstack-query';
90
+
91
+ // Global queryClient
92
+ const queryClient = new QueryClient();
93
+
94
+ // do this before adding the queryClient to QueryClientProvider
95
+ bootstrapQueryRequest(queryClient);
96
+
97
+ // recommended setup for mobile apps as the .env setup won't work
98
+ bootstrapQueryRequest(queryClient, {
99
+ context: 'app', // this is required to make the library switch to app context where necessary
100
+ environments: {
101
+ appBaseUrl: baseUrl,
102
+ appTimeout: 30000,
103
+ },
104
+ modelConfig: {
105
+ idColumn: 'id', // used for useQueryModel to uniquely identify query data in a collection/array instance
106
+ },
107
+ });
108
+ ```
109
+
110
+ You can now use it in a QueryClientProvider
111
+
112
+ ```jsx
113
+ import { QueryClientProvider } from '@tanstack/react-query';
114
+ import { queryClient } from './queryClient';
115
+
116
+ function App() {
117
+ return (
118
+ <QueryClientProvider client={queryClient}>
119
+ <HomePage />
120
+ <About />
121
+ </QueryClientProvider>
122
+ );
123
+ }
124
+ ```
125
+
126
+ Updating the configurations inside a component
127
+
128
+ ```jsx
129
+ import { useQueryBaseURL, useQueryHeaders, useQueryTimeout } from '@ventlio/tanstack-query';
130
+
131
+ function LoginPage() {
132
+ const { headers, setQueryHeaders } = useQueryHeaders();
133
+ const [authToken, setAuthToken] = useState();
134
+ useEffect(() => {
135
+ // after user has logged in successfully set the authorization header token
136
+ // this should also be done mostly in the layout that contains the authenticated views of the app
137
+ // for instance in AuthLayout, so that after login in the authToken can still be used to authenticate future request
138
+ // when user refreshes the page
139
+ setQueryHeaders({ Authorization: `Bearer ${authToken}` });
140
+ }, []);
141
+
142
+ return <>{/** codes */}</>;
143
+ }
144
+ ```
145
+
146
+ # Hooks
147
+
148
+ ## useGetRequest Hook
149
+
150
+ The `useGetRequest` hook is a custom React Query hook that handles GET requests. It returns an object that contains the current state of the query, as well as several methods to update the query.
151
+
152
+ ## Parameters
153
+
154
+ The `useGetRequest` hook takes an object as its parameter with the following properties:
155
+
156
+ - `path`: a string representing the URL path for the GET request. Required.
157
+ - `load`: a boolean indicating whether to load the query immediately. Default: `false`.
158
+ - `queryOptions`: an object containing additional options for the query. Optional.
159
+ - `keyTracker`: a string that tracks changes to the query key. Optional.
160
+
161
+ ## Return Value
162
+
163
+ The `useGetRequest` hook returns an object with the following properties:
164
+
165
+ - `data`: the data returned by the query, if successful.
166
+ - `isLoading`: a boolean indicating whether the query is currently loading.
167
+ - `isError`: a boolean indicating whether the query resulted in an error.
168
+ - `error`: the error message, if an error occurred.
169
+ - `updatePath`: a function that updates the path of the query.
170
+ - `nextPage`: a function that navigates to the next page of results, if pagination is present.
171
+ - `prevPage`: a function that navigates to the previous page of results, if pagination is present.
172
+ - `get`: a function that updates the path and options of the query and returns the data.
173
+ - `gotoPage`: a function that navigates to a specific page of results, if pagination is present.
174
+ - `page`: the current page number, if pagination is present.
175
+ - `queryKey`: an array representing the query key.
176
+
177
+ ## Example Usage
178
+
179
+ ```jsx
180
+ import { useGetRequest } from '@ventlio/tanstack-query';
181
+
182
+ const MyComponent = () => {
183
+ const { data, isLoading, isError, error, updatePath, nextPage, prevPage, get, gotoPage, page, queryKey } =
184
+ useGetRequest({
185
+ path: '/api/mydata',
186
+ load: true,
187
+ queryOptions: {
188
+ staleTime: 10000,
189
+ refetchOnWindowFocus: false,
190
+ },
191
+ keyTracker: 'mydata',
192
+ });
193
+
194
+ return (
195
+ <div>
196
+ {isLoading && <p>Loading...</p>}
197
+ {isError && <p>{error.message}</p>}
198
+ {data && (
199
+ <ul>
200
+ {data.map((item) => (
201
+ <li key={item.id}>{item.name}</li>
202
+ ))}
203
+ </ul>
204
+ )}
205
+ <button onClick={() => nextPage()}>Next Page</button>
206
+ <button onClick={() => prevPage()}>Previous Page</button>
207
+ <button onClick={() => gotoPage(1)}>Go to Page 1</button>
208
+ <button onClick={() => get('/api/mydata?page=2')}>Get Page 2</button>
209
+ </div>
210
+ );
211
+ };
212
+ ```
213
+
214
+ ## `usePostRequest` Hook
215
+
216
+ The `usePostRequest` function is a custom React hook that provides an easy way to make POST requests using the `@tanstack/react-query` library.
217
+
218
+ ## Usage
219
+
220
+ To use the `usePostRequest` hook, import it from the module where it's defined and call it in your component like this:
221
+
222
+ ```jsx
223
+ import { usePostRequest } from '@ventlio/tanstack-query';
224
+
225
+ const MyComponent = () => {
226
+ const { post, isLoading, isError, isSuccess, data, error } = usePostRequest({
227
+ path: '/api/posts',
228
+ isFormData: true,
229
+ });
230
+
231
+ const handleFormSubmit = async (formData) => {
232
+ try {
233
+ const response = await post(formData);
234
+ console.log(response);
235
+ } catch (e) {
236
+ console.error(e);
237
+ }
238
+ };
239
+
240
+ return (
241
+ <form onSubmit={handleFormSubmit}>
242
+ {/* form inputs */}
243
+ <button type="submit">Submit</button>
244
+ </form>
245
+ );
246
+ };
247
+ ```
248
+
249
+ ## Parameters
250
+
251
+ The `usePostRequest` hook takes an object with two optional properties:
252
+
253
+ - `path` (required): the URL path to make the POST request to.
254
+ - `isFormData` (optional, default is `false`): a boolean that indicates whether to send the request data as form data.
255
+
256
+ ## Returns
257
+
258
+ The `usePostRequest` hook returns an object with the following properties:
259
+
260
+ - `post`: a function that takes the data to be sent in the request and an optional `MutateOptions` object, and returns a promise that resolves to the response data.
261
+ - `isLoading`: a boolean that indicates whether the request is currently loading.
262
+ - `isError`: a boolean that indicates whether the request resulted in an error.
263
+ - `isSuccess`: a boolean that indicates whether the request was successful.
264
+ - `data`: the response data, if the request was successful.
265
+ - `error`: the error object, if the request resulted in an error.
266
+
267
+ ## Implementation Details
268
+
269
+ The `usePostRequest` hook internally uses the `useMutation` hook from the `@tanstack/react-query` library to register a mutation that sends the POST request. It also uses the internal `makeRequest` function to actually make the request.
270
+
271
+ It users the `useQueryConfig` hook internally to get the `headers`, `baseURL`, and `timeout` values that are passed to `makeRequest`.
272
+
273
+ If the request is successful, the hook scrolls the page to the top using the `window.scrollTo` method. If the request fails, it also scrolls to the top before throwing the error.
274
+
275
+ ## `usePatchRequest` Hook
276
+
277
+ `usePatchRequest` is a React hook that allows you to make PATCH requests. It takes in a `path` parameter that specifies the path of the API endpoint to call.
278
+
279
+ ```typescript
280
+ usePatchRequest<TResponse>({ path: string }): { patch, ...mutation }
281
+ ```
282
+
283
+ ### Parameters
284
+
285
+ - `path` (required): A string that represents the path of the API endpoint to call.
286
+
287
+ ### Return Values
288
+
289
+ `usePatchRequest` returns an object with the following properties:
290
+
291
+ - `patch`: A function that can be called to initiate a PATCH request.
292
+ - `...mutation`: The rest of the properties returned by the `useMutation` hook.
293
+
294
+ ### Example
295
+
296
+ ```jsx
297
+ import { usePatchRequest } from '@ventlio/tanstack-query';
298
+
299
+ function App() {
300
+ const { patch, isLoading, isError, isSuccess, data } =
301
+ usePatchRequest<User>(
302
+ {
303
+ path: '/users/1',
304
+ });
305
+
306
+ const updateUser = async (user: User) => {
307
+ await patch(user);
308
+ };
309
+
310
+ return (
311
+ <div>
312
+ <button onClick={() => updateUser({ name: 'John' })}>Update User</button>
313
+ {isLoading && <div>Loading...</div>}
314
+ {isError && <div>Error updating user</div>}
315
+ {isSuccess && <div>Successfully updated user {data?.name}</div>}
316
+ </div>
317
+ );
318
+ }
319
+ ```
320
+
321
+ In this example, we are using the `usePatchRequest` hook to send a PATCH request to update a user's name. We call the `patch` function with the new user data to initiate the request. The `isLoading`, `isError`, `isSuccess`, and `data` properties are used to display the request status and response data.
322
+
323
+ Note that we have assumed the existence of a `User` interface in this example.
324
+
325
+ ## `useDeleteRequest` Hook
326
+
327
+ The `useDeleteRequest` hook is a custom hook used to make HTTP DELETE requests using `@tanstack/react-query` library. This hook returns an object that contains a `destroy` function and other properties inherited from the `useQuery` hook.
328
+
329
+ ### Parameters
330
+
331
+ This hook does not take any parameter.
332
+
333
+ ### Return value
334
+
335
+ The hook returns an object containing:
336
+
337
+ - `destroy`: a function used to make the DELETE request and returns the server's response.
338
+ - Other properties inherited from the `useQuery` hook.
339
+
340
+ ### Example
341
+
342
+ Here's an example of how to use the `useDeleteRequest` hook:
343
+
344
+ ```jsx
345
+ import { useDeleteRequest } from '@ventlio/tanstack-query';
346
+
347
+ function DeleteButton({ link }) {
348
+ const { isLoading, isError, error, data, destroy } = useDeleteRequest();
349
+
350
+ const handleDelete = async () => {
351
+ const response = await destroy(link);
352
+ // do something with the response
353
+ };
354
+
355
+ return (
356
+ <button onClick={handleDelete} disabled={isLoading}>
357
+ {isLoading ? 'Deleting...' : 'Delete'}
358
+ </button>
359
+ );
360
+ }
361
+ ```
362
+
363
+ In the above example, we created a `DeleteButton` component that uses the `useDeleteRequest` hook to make a DELETE request to the specified `link` when the button is clicked. The `destroy` function returns the server's response, which we can then use to update the UI.
364
+
365
+ # useRefetchQuery
366
+
367
+ A simple utility function that utilizes `useQueryClient` hook from `@tanstack/react-query` to refetch a query and retrieve updated data.
368
+
369
+ ## Usage
370
+
371
+ 1. Import `useRefetchQuery` from your desired file:
372
+
373
+ ```javascript
374
+ import { useRefetchQuery } from '@ventlio/tanstack-query';
375
+ ```
376
+
377
+ 2. Call `useRefetchQuery` with a `queryKey` parameter which is an array of any types that uniquely identifies the query:
378
+
379
+ ```javascript
380
+ const { refetchQuery } = useRefetchQuery(['myQueryKey']);
381
+ ```
382
+
383
+ 3. Invoke `refetchQuery` function to refetch the query and retrieve updated data:
384
+
385
+ ```javascript
386
+ const { data } = await refetchQuery<MyDataType>();
387
+ ```
388
+
389
+ If you want to refetch a different query, you can pass a different `queryKey` parameter to `refetchQuery` function:
390
+
391
+ ```javascript
392
+ const { data } = (await refetchQuery) < MyDataType > ['myOtherQueryKey'];
393
+ ```
394
+
395
+ If you want to perform additional operations after refetching the query, you can use the `data` returned by `refetchQuery` function:
396
+
397
+ ```javascript
398
+ const { data } = await refetchQuery<MyDataType>();
399
+ // Perform additional operations with data
400
+ ```
401
+
402
+ ## Parameters
403
+
404
+ - `queryKey`: An array of any types that uniquely identifies the query.
405
+
406
+ ## Return Value
407
+
408
+ - `refetchQuery`: A function that refetches the query and retrieves updated data.
409
+
410
+ ## Example
411
+
412
+ ```javascript
413
+ import { useQueryClient } from '@tanstack/react-query';
414
+ import { useRefetchQuery } from '@ventlio/tanstack-query';
415
+
416
+ const MyComponent = () => {
417
+ const queryClient = useQueryClient();
418
+
419
+ const { refetchQuery } = useRefetchQuery(['myQueryKey']);
420
+
421
+ const handleClick = async () => {
422
+ try {
423
+ // Refetch the query and retrieve updated data
424
+ const { data } = await refetchQuery<MyDataType>();
425
+
426
+ // Perform additional operations with data
427
+ console.log(data);
428
+ } catch (error) {
429
+ // Handle error
430
+ console.error(error);
431
+ }
432
+ };
433
+
434
+ return (
435
+ <button onClick={handleClick}>
436
+ Refetch Query
437
+ </button>
438
+ );
439
+ };
440
+ ```
441
+
442
+ # useKeyTrackerModel
443
+
444
+ A custom hook that utilizes `useQueryClient` hook from `@tanstack/react-query` and `useState` hook from `react` to track a query key and retrieve query data.
445
+
446
+ ## Usage
447
+
448
+ 1. Import `useKeyTrackerModel` from @ventlio/tanstack-query:
449
+
450
+ ```javascript
451
+ import { useKeyTrackerModel } from '@ventlio/tanstack-query';
452
+ ```
453
+
454
+ 2. Call `useKeyTrackerModel` with a `keyTracker` parameter which is a string that uniquely identifies the query key:
455
+
456
+ ```javascript
457
+ const { refetchQuery, getQueryKey, queryKey, data } = useKeyTrackerModel < MyDataType > 'myKeyTracker';
458
+ ```
459
+
460
+ 3. Invoke `getQueryKey` function to retrieve the query key:
461
+
462
+ ```javascript
463
+ const key = getQueryKey();
464
+ ```
465
+
466
+ 4. Invoke `refetchQuery` function to retrieve query data:
467
+
468
+ ```javascript
469
+ const queryData = refetchQuery();
470
+ ```
471
+
472
+ 5. Use `queryKey` and `data` as needed in your component:
473
+
474
+ ```javascript
475
+ return (
476
+ <div>
477
+ <p>Query Key: {queryKey}</p>
478
+ <p>Query Data: {data}</p>
479
+ </div>
480
+ );
481
+ ```
482
+
483
+ ## Parameters
484
+
485
+ - `keyTracker`: A string that uniquely identifies the query key.
486
+
487
+ ## Return Value
488
+
489
+ - `refetchQuery`: A function that retrieves query data.
490
+ - `getQueryKey`: A function that retrieves the query key.
491
+ - `queryKey`: The query key.
492
+ - `data`: The query data.
493
+
494
+ ## Example
495
+
496
+ ```javascript
497
+ import { useQueryClient } from '@tanstack/react-query';
498
+ import { useState } from 'react';
499
+ import { useKeyTrackerModel } from '@ventlio/tanstack-query';
500
+
501
+ const MyComponent = () => {
502
+ const queryClient = useQueryClient();
503
+
504
+ const { refetchQuery, getQueryKey, queryKey, data } = useKeyTrackerModel < MyDataType > 'myKeyTracker';
505
+
506
+ const handleClick = async () => {
507
+ // Retrieve the query key
508
+ const key = getQueryKey();
509
+
510
+ // Retrieve query data
511
+ const queryData = refetchQuery();
512
+
513
+ // Perform additional operations with query key and data
514
+ console.log(key, queryData);
515
+ };
516
+
517
+ return (
518
+ <div>
519
+ <button onClick={handleClick}>Get Query Data</button>
520
+ <p>Query Key: {queryKey}</p>
521
+ <p>Query Data: {data}</p>
522
+ </div>
523
+ );
524
+ };
525
+ ```
526
+
527
+ ## Contributing
528
+
529
+ Contributions to this codebase are welcome. If you find any issues or have any suggestions, please feel free to create an issue or pull request.
530
+
531
+ ## License
532
+
533
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,4 @@
1
+ import type { QueryClient } from '@tanstack/react-query';
2
+ import 'url-search-params-polyfill';
3
+ import type { BootstrapConfig } from '../types';
4
+ export declare const bootstrapQueryRequest: (queryClient: QueryClient, options?: BootstrapConfig) => void;
@@ -0,0 +1,19 @@
1
+ import 'url-search-params-polyfill';
2
+
3
+ const bootstrapQueryRequest = (queryClient, options) => {
4
+ // make query config doesn't expire
5
+ queryClient.setQueryDefaults(['config'], {
6
+ staleTime: Infinity,
7
+ cacheTime: Infinity,
8
+ });
9
+ // set default query config
10
+ queryClient.setQueryData(['config'], {
11
+ headers: {
12
+ Authorization: ``,
13
+ },
14
+ options,
15
+ });
16
+ };
17
+
18
+ export { bootstrapQueryRequest };
19
+ //# sourceMappingURL=bootstrapQueryRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrapQueryRequest.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,4 @@
1
+ export interface IConfig {
2
+ API_URL: string;
3
+ TIMEOUT: number;
4
+ }
@@ -1,4 +1,6 @@
1
- export * from './useQueryBaseURL';
1
+ export * from './bootstrapQueryRequest';
2
+ export * from './config.interface';
3
+ export * from './useEnvironmentVariables';
2
4
  export * from './useQueryConfig';
3
5
  export * from './useQueryHeaders';
4
- export * from './useQueryTimeout';
6
+ export * from './useReactNativeEnv';
@@ -0,0 +1,2 @@
1
+ import type { IConfig } from './config.interface';
2
+ export declare const useEnvironmentVariables: () => IConfig;
@@ -0,0 +1,14 @@
1
+ import { useReactNativeEnv } from './useReactNativeEnv.js';
2
+
3
+ const useEnvironmentVariables = () => {
4
+ const { appTimeout, appUrl } = useReactNativeEnv();
5
+ const url = process.env.REACT_APP_API_URL ?? process.env.NEXT_PUBLIC_API_URL ?? appUrl;
6
+ const timeout = process.env.REACT_APP_API_TIMEOUT ?? process.env.NEXT_PUBLIC_API_TIMEOUT ?? appTimeout;
7
+ return {
8
+ API_URL: url,
9
+ TIMEOUT: Number(timeout),
10
+ };
11
+ };
12
+
13
+ export { useEnvironmentVariables };
14
+ //# sourceMappingURL=useEnvironmentVariables.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useEnvironmentVariables.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
@@ -1,14 +1,10 @@
1
- 'use strict';
2
-
3
- var reactQuery = require('@tanstack/react-query');
1
+ import { useQueryClient } from '@tanstack/react-query';
4
2
 
5
3
  const useQueryConfig = () => {
6
- const queryClient = reactQuery.useQueryClient();
7
- const { headers, baseURL, timeout } = queryClient.getQueryData([
8
- 'config',
9
- ]);
10
- return { headers, baseURL, timeout };
4
+ const queryClient = useQueryClient();
5
+ const { headers = {}, options = {} } = queryClient.getQueryData(['config']) ?? {};
6
+ return { headers, options };
11
7
  };
12
8
 
13
- exports.useQueryConfig = useQueryConfig;
9
+ export { useQueryConfig };
14
10
  //# sourceMappingURL=useQueryConfig.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useQueryConfig.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"useQueryConfig.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
@@ -1,19 +1,28 @@
1
- 'use strict';
2
-
3
- var reactQuery = require('@tanstack/react-query');
4
- var useQueryConfig = require('./useQueryConfig.js');
1
+ import { useQueryClient } from '@tanstack/react-query';
2
+ import { getDateInFuture } from '../helpers/timeFuncs.js';
5
3
 
6
4
  const useQueryHeaders = () => {
7
- const { headers } = useQueryConfig.useQueryConfig();
8
- const queryClient = reactQuery.useQueryClient();
5
+ const queryClient = useQueryClient();
6
+ const getHeaders = () => {
7
+ const config = queryClient.getQueryData(['config']);
8
+ return config.headers;
9
+ };
9
10
  const setQueryHeaders = (newHeaders) => {
11
+ // make sure the config does not expire
12
+ queryClient.setQueryDefaults(['config'], {
13
+ staleTime: Infinity,
14
+ cacheTime: Infinity,
15
+ });
16
+ // set the config
10
17
  queryClient.setQueryData(['config'], (config) => {
11
- config.headers = newHeaders;
12
- return config;
18
+ const newConfig = { ...config, headers: newHeaders };
19
+ return newConfig;
20
+ }, {
21
+ updatedAt: getDateInFuture(2),
13
22
  });
14
23
  };
15
- return { headers, setQueryHeaders };
24
+ return { setQueryHeaders, getHeaders };
16
25
  };
17
26
 
18
- exports.useQueryHeaders = useQueryHeaders;
27
+ export { useQueryHeaders };
19
28
  //# sourceMappingURL=useQueryHeaders.js.map