@ventlio/tanstack-query 0.2.17 → 0.2.19

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 (3) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +376 -40
  3. package/package.json +2 -2
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
@@ -92,69 +92,405 @@ function LoginPage() {
92
92
  }
93
93
  ```
94
94
 
95
- ## Hooks
95
+ # Hooks
96
96
 
97
- - `useQueryBaseURL()`
98
- return
97
+ ## useGetRequest Hook
99
98
 
100
- - `baseURL: string`; the global baseURL
101
- - `setBaseURL(url: string)`; update the global baseURL
99
+ 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.
102
100
 
103
- - `useQueryHeaders()`
104
- return
101
+ ## Parameters
105
102
 
106
- - `headers: RawAxiosRequestHeaders`; the global request headers
107
- - `setHeaders(headers: RawAxiosRequestHeaders)`; update the global request headers
103
+ The `useGetRequest` hook takes an object as its parameter with the following properties:
108
104
 
109
- - `useGetRequest<T>(config: { path, load, queryOptions })`
105
+ - `path`: a string representing the URL path for the GET request. Required.
106
+ - `load`: a boolean indicating whether to load the query immediately. Default: `false`.
107
+ - `queryOptions`: an object containing additional options for the query. Optional.
108
+ - `keyTracker`: a string that tracks changes to the query key. Optional.
110
109
 
111
- - params
112
- - config
113
- - `path: string`: request path
114
- - `load: boolean`: if true the request starts immediately otherwise it will wait until it is triggered to true, defaults to false
115
- - `queryOptions: TanstackQueryOption<TResponse>`: query options
116
- - `keyTracker`: query key tracker for dynamic queries
110
+ ## Return Value
117
111
 
118
- - `usePostRequest<T>(config: { path, isFormData })`
112
+ The `useGetRequest` hook returns an object with the following properties:
119
113
 
120
- - params
121
- - config
122
- - `path: string`: request path
123
- - `isFormData: boolean`: set it to true if you want to upload file with the post request
114
+ - `data`: the data returned by the query, if successful.
115
+ - `isLoading`: a boolean indicating whether the query is currently loading.
116
+ - `isError`: a boolean indicating whether the query resulted in an error.
117
+ - `error`: the error message, if an error occurred.
118
+ - `updatePath`: a function that updates the path of the query.
119
+ - `nextPage`: a function that navigates to the next page of results, if pagination is present.
120
+ - `prevPage`: a function that navigates to the previous page of results, if pagination is present.
121
+ - `get`: a function that updates the path and options of the query and returns the data.
122
+ - `gotoPage`: a function that navigates to a specific page of results, if pagination is present.
123
+ - `page`: the current page number, if pagination is present.
124
+ - `queryKey`: an array representing the query key.
124
125
 
125
- - `useDeleteRequest<T>()`
126
+ ## Example Usage
126
127
 
127
- - params
128
- - no params
128
+ ```jsx
129
+ import { useGetRequest } from '@ventlio/tanstack-query';
129
130
 
130
- - `usePatchRequest<T>({ path })`
131
- - params
132
- - `path : string`: path to the request to be deleted
131
+ const MyComponent = () => {
132
+ const {
133
+ data,
134
+ isLoading,
135
+ isError,
136
+ error,
137
+ updatePath,
138
+ nextPage,
139
+ prevPage,
140
+ get,
141
+ gotoPage,
142
+ page,
143
+ queryKey,
144
+ } = useGetRequest({
145
+ path: '/api/mydata',
146
+ load: true,
147
+ queryOptions: {
148
+ staleTime: 10000,
149
+ refetchOnWindowFocus: false,
150
+ },
151
+ keyTracker: 'mydata',
152
+ });
133
153
 
134
- ## Examples
154
+ return (
155
+ <div>
156
+ {isLoading && <p>Loading...</p>}
157
+ {isError && <p>{error.message}</p>}
158
+ {data && (
159
+ <ul>
160
+ {data.map((item) => (
161
+ <li key={item.id}>{item.name}</li>
162
+ ))}
163
+ </ul>
164
+ )}
165
+ <button onClick={() => nextPage()}>Next Page</button>
166
+ <button onClick={() => prevPage()}>Previous Page</button>
167
+ <button onClick={() => gotoPage(1)}>Go to Page 1</button>
168
+ <button onClick={() => get('/api/mydata?page=2')}>Get Page 2</button>
169
+ </div>
170
+ );
171
+ };
172
+ ```
173
+
174
+ ## `usePostRequest` Hook
175
+
176
+ The `usePostRequest` function is a custom React hook that provides an easy way to make POST requests using the `@tanstack/react-query` library.
177
+
178
+ ## Usage
135
179
 
136
- Make fetch Request
180
+ To use the `usePostRequest` hook, import it from the module where it's defined and call it in your component like this:
137
181
 
138
182
  ```jsx
139
- import { useGetRequest } from '@ventlio/tanstack-query';
183
+ import { usePostRequest } from '@ventlio/tanstack-query';
140
184
 
141
- function PostPage() {
142
- const { isLoading, data, isInitialLoading, get } = useGetRequest({
143
- path: '/posts/1',
144
- load: true,
185
+ const MyComponent = () => {
186
+ const { post, isLoading, isError, isSuccess, data, error } = usePostRequest({
187
+ path: '/api/posts',
188
+ isFormData: true,
145
189
  });
146
190
 
147
- if (isLoading || isInitialLoading || !data) {
148
- return <LoadingSpinner />;
149
- }
191
+ const handleFormSubmit = async (formData) => {
192
+ try {
193
+ const response = await post(formData);
194
+ console.log(response);
195
+ } catch (e) {
196
+ console.error(e);
197
+ }
198
+ };
199
+
200
+ return (
201
+ <form onSubmit={handleFormSubmit}>
202
+ {/* form inputs */}
203
+ <button type="submit">Submit</button>
204
+ </form>
205
+ );
206
+ };
207
+ ```
208
+
209
+ ## Parameters
210
+
211
+ The `usePostRequest` hook takes an object with two optional properties:
212
+
213
+ - `path` (required): the URL path to make the POST request to.
214
+ - `isFormData` (optional, default is `false`): a boolean that indicates whether to send the request data as form data.
215
+
216
+ ## Returns
217
+
218
+ The `usePostRequest` hook returns an object with the following properties:
219
+
220
+ - `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.
221
+ - `isLoading`: a boolean that indicates whether the request is currently loading.
222
+ - `isError`: a boolean that indicates whether the request resulted in an error.
223
+ - `isSuccess`: a boolean that indicates whether the request was successful.
224
+ - `data`: the response data, if the request was successful.
225
+ - `error`: the error object, if the request resulted in an error.
226
+
227
+ ## Implementation Details
228
+
229
+ 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.
230
+
231
+ It users the `useQueryConfig` hook internally to get the `headers`, `baseURL`, and `timeout` values that are passed to `makeRequest`.
232
+
233
+ 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.
234
+
235
+ ## `usePatchRequest` Hook
236
+
237
+ `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.
238
+
239
+ ```typescript
240
+ usePatchRequest<TResponse>({ path: string }): { patch, ...mutation }
241
+ ```
242
+
243
+ ### Parameters
244
+
245
+ - `path` (required): A string that represents the path of the API endpoint to call.
246
+
247
+ ### Return Values
248
+
249
+ `usePatchRequest` returns an object with the following properties:
250
+
251
+ - `patch`: A function that can be called to initiate a PATCH request.
252
+ - `...mutation`: The rest of the properties returned by the `useMutation` hook.
253
+
254
+ ### Example
255
+
256
+ ```jsx
257
+ import { usePatchRequest } from '@ventlio/tanstack-query';
258
+
259
+ function App() {
260
+ const { patch, isLoading, isError, isSuccess, data } =
261
+ usePatchRequest <
262
+ User >
263
+ {
264
+ path: '/users/1',
265
+ };
266
+
267
+ const updateUser = async (user: User) => {
268
+ await patch(user);
269
+ };
150
270
 
151
271
  return (
152
272
  <div>
153
- <h1> {data.data.title} </h1>
154
- <article> {data.data.description} </article>
273
+ <button onClick={() => updateUser({ name: 'John' })}>Update User</button>
274
+ {isLoading && <div>Loading...</div>}
275
+ {isError && <div>Error updating user</div>}
276
+ {isSuccess && <div>Successfully updated user {data?.name}</div>}
155
277
  </div>
156
278
  );
157
279
  }
158
280
  ```
159
281
 
160
- ## We welcome any contribution that will help the project
282
+ 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.
283
+
284
+ Note that we have assumed the existence of a `User` interface in this example.
285
+
286
+ ## `useDeleteRequest` Hook
287
+
288
+ 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.
289
+
290
+ ### Parameters
291
+
292
+ This hook does not take any parameter.
293
+
294
+ ### Return value
295
+
296
+ The hook returns an object containing:
297
+
298
+ - `destroy`: a function used to make the DELETE request and returns the server's response.
299
+ - Other properties inherited from the `useQuery` hook.
300
+
301
+ ### Example
302
+
303
+ Here's an example of how to use the `useDeleteRequest` hook:
304
+
305
+ ```jsx
306
+ import { useDeleteRequest } from '@ventlio/tanstack-query';
307
+
308
+ function DeleteButton({ link }) {
309
+ const { isLoading, isError, error, data, destroy } = useDeleteRequest();
310
+
311
+ const handleDelete = async () => {
312
+ const response = await destroy(link);
313
+ // do something with the response
314
+ };
315
+
316
+ return (
317
+ <button onClick={handleDelete} disabled={isLoading}>
318
+ {isLoading ? 'Deleting...' : 'Delete'}
319
+ </button>
320
+ );
321
+ }
322
+ ```
323
+
324
+ 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.
325
+
326
+ # useRefetchQuery
327
+
328
+ A simple utility function that utilizes `useQueryClient` hook from `@tanstack/react-query` to refetch a query and retrieve updated data.
329
+
330
+ ## Usage
331
+
332
+ 1. Import `useRefetchQuery` from your desired file:
333
+
334
+ ```javascript
335
+ import { useRefetchQuery } from '@ventlio/tanstack-query';
336
+ ```
337
+
338
+ 2. Call `useRefetchQuery` with a `queryKey` parameter which is an array of any types that uniquely identifies the query:
339
+
340
+ ```javascript
341
+ const { refetchQuery } = useRefetchQuery(['myQueryKey']);
342
+ ```
343
+
344
+ 3. Invoke `refetchQuery` function to refetch the query and retrieve updated data:
345
+
346
+ ```javascript
347
+ const { data } = await refetchQuery<MyDataType>();
348
+ ```
349
+
350
+ If you want to refetch a different query, you can pass a different `queryKey` parameter to `refetchQuery` function:
351
+
352
+ ```javascript
353
+ const { data } = (await refetchQuery) < MyDataType > ['myOtherQueryKey'];
354
+ ```
355
+
356
+ If you want to perform additional operations after refetching the query, you can use the `data` returned by `refetchQuery` function:
357
+
358
+ ```javascript
359
+ const { data } = await refetchQuery<MyDataType>();
360
+ // Perform additional operations with data
361
+ ```
362
+
363
+ ## Parameters
364
+
365
+ - `queryKey`: An array of any types that uniquely identifies the query.
366
+
367
+ ## Return Value
368
+
369
+ - `refetchQuery`: A function that refetches the query and retrieves updated data.
370
+
371
+ ## Example
372
+
373
+ ```javascript
374
+ import { useQueryClient } from '@tanstack/react-query';
375
+ import { useRefetchQuery } from '@ventlio/tanstack-query';
376
+
377
+ const MyComponent = () => {
378
+ const queryClient = useQueryClient();
379
+
380
+ const { refetchQuery } = useRefetchQuery(['myQueryKey']);
381
+
382
+ const handleClick = async () => {
383
+ try {
384
+ // Refetch the query and retrieve updated data
385
+ const { data } = await refetchQuery<MyDataType>();
386
+
387
+ // Perform additional operations with data
388
+ console.log(data);
389
+ } catch (error) {
390
+ // Handle error
391
+ console.error(error);
392
+ }
393
+ };
394
+
395
+ return (
396
+ <button onClick={handleClick}>
397
+ Refetch Query
398
+ </button>
399
+ );
400
+ };
401
+ ```
402
+
403
+ # useKeyTrackerModel
404
+
405
+ 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.
406
+
407
+ ## Usage
408
+
409
+ 1. Import `useKeyTrackerModel` from @ventlio/tanstack-query:
410
+
411
+ ```javascript
412
+ import { useKeyTrackerModel } from '@ventlio/tanstack-query';
413
+ ```
414
+
415
+ 2. Call `useKeyTrackerModel` with a `keyTracker` parameter which is a string that uniquely identifies the query key:
416
+
417
+ ```javascript
418
+ const { refetchQuery, getQueryKey, queryKey, data } =
419
+ useKeyTrackerModel < MyDataType > 'myKeyTracker';
420
+ ```
421
+
422
+ 3. Invoke `getQueryKey` function to retrieve the query key:
423
+
424
+ ```javascript
425
+ const key = getQueryKey();
426
+ ```
427
+
428
+ 4. Invoke `refetchQuery` function to retrieve query data:
429
+
430
+ ```javascript
431
+ const queryData = refetchQuery();
432
+ ```
433
+
434
+ 5. Use `queryKey` and `data` as needed in your component:
435
+
436
+ ```javascript
437
+ return (
438
+ <div>
439
+ <p>Query Key: {queryKey}</p>
440
+ <p>Query Data: {data}</p>
441
+ </div>
442
+ );
443
+ ```
444
+
445
+ ## Parameters
446
+
447
+ - `keyTracker`: A string that uniquely identifies the query key.
448
+
449
+ ## Return Value
450
+
451
+ - `refetchQuery`: A function that retrieves query data.
452
+ - `getQueryKey`: A function that retrieves the query key.
453
+ - `queryKey`: The query key.
454
+ - `data`: The query data.
455
+
456
+ ## Example
457
+
458
+ ```javascript
459
+ import { useQueryClient } from '@tanstack/react-query';
460
+ import { useState } from 'react';
461
+ import { useKeyTrackerModel } from '@ventlio/tanstack-query';
462
+
463
+ const MyComponent = () => {
464
+ const queryClient = useQueryClient();
465
+
466
+ const { refetchQuery, getQueryKey, queryKey, data } =
467
+ useKeyTrackerModel < MyDataType > 'myKeyTracker';
468
+
469
+ const handleClick = async () => {
470
+ // Retrieve the query key
471
+ const key = getQueryKey();
472
+
473
+ // Retrieve query data
474
+ const queryData = refetchQuery();
475
+
476
+ // Perform additional operations with query key and data
477
+ console.log(key, queryData);
478
+ };
479
+
480
+ return (
481
+ <div>
482
+ <button onClick={handleClick}>Get Query Data</button>
483
+ <p>Query Key: {queryKey}</p>
484
+ <p>Query Data: {data}</p>
485
+ </div>
486
+ );
487
+ };
488
+ ```
489
+
490
+ ## Contributing
491
+
492
+ 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.
493
+
494
+ ## License
495
+
496
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ventlio/tanstack-query",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "contributors": [
@@ -12,7 +12,7 @@
12
12
  ],
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "https://github.com/ventlio-tech/tanstact-query.git"
15
+ "url": "https://github.com/ventlio-tech/tanstack-query.git"
16
16
  },
17
17
  "types": "dist/index.d.ts",
18
18
  "author": {