react-api-kit 1.0.4 β 1.0.6
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.
- package/README.md +328 -65
- package/dist/react-api-kit.mjs +34 -27
- package/dist/react-api-kit.umd.js +1 -1
- package/package.json +1 -2
package/README.md
CHANGED
|
@@ -1,133 +1,396 @@
|
|
|
1
|
-
# π
|
|
1
|
+
# π react-api-kit
|
|
2
2
|
|
|
3
|
-
A lightweight,
|
|
3
|
+
A lightweight, production-ready API client built on **Axios** + **TanStack Query** for React applications.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
β
|
|
9
|
-
β
|
|
5
|
+
[](https://www.npmjs.com/package/react-api-kit)
|
|
6
|
+
[](./LICENSE)
|
|
7
|
+
|
|
8
|
+
β Auto Bearer / Token / Custom auth headers
|
|
9
|
+
β Custom static headers per project
|
|
10
|
+
β Global error handling with toast support
|
|
11
|
+
β Auto logout on 401
|
|
12
|
+
β React Queryβready hooks (GET, POST, PUT, PATCH, DELETE)
|
|
13
|
+
β No UI dependencies β works with any toast library
|
|
10
14
|
|
|
11
15
|
---
|
|
12
16
|
|
|
13
17
|
## π¦ Installation
|
|
14
18
|
|
|
15
19
|
```bash
|
|
16
|
-
npm install axios @tanstack/react-query
|
|
20
|
+
npm install react-api-kit axios @tanstack/react-query
|
|
17
21
|
```
|
|
18
22
|
|
|
19
|
-
> **Peer
|
|
23
|
+
> **Peer Dependencies:** React β₯ 17, Axios β₯ 1, TanStack Query β₯ 4
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
- TanStack Query v5+
|
|
25
|
+
---
|
|
23
26
|
|
|
24
|
-
##
|
|
27
|
+
## β‘ Quick Start
|
|
25
28
|
|
|
26
|
-
### 1
|
|
29
|
+
### 1. Wrap your app with React Query Provider
|
|
27
30
|
|
|
28
31
|
```tsx
|
|
32
|
+
// main.tsx
|
|
29
33
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
30
34
|
|
|
31
35
|
const queryClient = new QueryClient();
|
|
32
36
|
|
|
33
|
-
export function
|
|
37
|
+
export default function App() {
|
|
34
38
|
return (
|
|
35
|
-
<QueryClientProvider client={queryClient}>
|
|
39
|
+
<QueryClientProvider client={queryClient}>
|
|
40
|
+
<YourApp />
|
|
41
|
+
</QueryClientProvider>
|
|
36
42
|
);
|
|
37
43
|
}
|
|
38
44
|
```
|
|
39
45
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
### 2οΈβ£ Configure the API (Required)
|
|
43
|
-
|
|
44
|
-
Call `setupApi` **once**, ideally at application startup.
|
|
46
|
+
### 2. Configure the API (once at app startup)
|
|
45
47
|
|
|
46
48
|
```ts
|
|
49
|
+
// api.config.ts
|
|
47
50
|
import { setupApi } from "react-api-kit";
|
|
48
|
-
import { toast } from "react-toastify";
|
|
49
51
|
|
|
50
52
|
setupApi({
|
|
51
|
-
baseURL: "
|
|
52
|
-
|
|
53
|
+
baseURL: "https://api.example.com",
|
|
54
|
+
tokenType: "Bearer",
|
|
53
55
|
getToken: () => localStorage.getItem("token"),
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Then import `api.config.ts` in your `main.tsx` before anything else.
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## π§ `setupApi` β Full Configuration
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
setupApi({
|
|
67
|
+
// βββ Required βββββββββββββββββββββββββββββββ
|
|
68
|
+
baseURL: "https://api.example.com",
|
|
69
|
+
|
|
70
|
+
// βββ Auth Token βββββββββββββββββββββββββββββ
|
|
71
|
+
tokenType: "Bearer", // "Bearer" | "Token" | "JWT" | "ApiKey" | any string
|
|
72
|
+
getToken: () => localStorage.getItem("token"), // return null to skip Authorization header
|
|
73
|
+
|
|
74
|
+
// βββ Custom Static Headers ββββββββββββββββββ
|
|
75
|
+
headers: {
|
|
76
|
+
"X-Api-Key": "your-api-key", // sent with every request
|
|
77
|
+
"Accept-Language": "en",
|
|
78
|
+
"X-App-Version": "1.0.0",
|
|
79
|
+
},
|
|
54
80
|
|
|
81
|
+
// βββ Toast Notifications ββββββββββββββββββββ
|
|
55
82
|
toast: {
|
|
56
83
|
success: (msg) => toast.success(msg),
|
|
57
|
-
error:
|
|
84
|
+
error: (msg) => toast.error(msg),
|
|
85
|
+
info: (msg) => toast.info(msg), // optional
|
|
86
|
+
warn: (msg) => toast.warn(msg), // optional
|
|
87
|
+
},
|
|
88
|
+
toastOptions: {
|
|
89
|
+
autoClose: 3000,
|
|
90
|
+
position: "top-right",
|
|
91
|
+
theme: "light", // "light" | "dark" | "colored"
|
|
58
92
|
},
|
|
59
93
|
|
|
94
|
+
// βββ Custom Error Messages βββββββββββββββββββ
|
|
60
95
|
errorMessages: {
|
|
61
|
-
401: "Session expired",
|
|
62
|
-
403: "Access denied",
|
|
63
|
-
|
|
96
|
+
401: "Session expired. Please login again.",
|
|
97
|
+
403: "Access denied.",
|
|
98
|
+
404: "Not found.",
|
|
99
|
+
500: "Server error. Try again later.",
|
|
64
100
|
},
|
|
65
101
|
|
|
66
|
-
|
|
67
|
-
|
|
102
|
+
// βββ Global Callbacks βββββββββββββββββββββββ
|
|
103
|
+
onSuccess: (data) => console.log("Success:", data),
|
|
104
|
+
onError: (error, message) => console.error("Error:", message),
|
|
105
|
+
onLogout: () => {
|
|
106
|
+
localStorage.clear();
|
|
107
|
+
window.location.href = "/login"; // auto-called on 401
|
|
68
108
|
},
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## π Auth Header β `tokenType` Examples
|
|
115
|
+
|
|
116
|
+
| `tokenType` | `getToken()` returns | Header sent |
|
|
117
|
+
|-------------|----------------------|-------------|
|
|
118
|
+
| `"Bearer"` *(default)* | `"abc123"` | `Authorization: Bearer abc123` |
|
|
119
|
+
| `"Token"` | `"abc123"` | `Authorization: Token abc123` |
|
|
120
|
+
| `"JWT"` | `"abc123"` | `Authorization: JWT abc123` |
|
|
121
|
+
| `"ApiKey"` | `"abc123"` | `Authorization: ApiKey abc123` |
|
|
122
|
+
| `""` *(empty)* | `"abc123"` | `Authorization: abc123` |
|
|
123
|
+
| *(not set)* | `"abc123"` | `Authorization: Bearer abc123` |
|
|
124
|
+
| `"Bearer"` | `null` / not set | *(no Authorization header)* |
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## π Custom Headers β `headers` Examples
|
|
129
|
+
|
|
130
|
+
Use `headers` for static values that never change (API keys, app identifiers, language, etc.):
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
// Single custom header
|
|
134
|
+
setupApi({
|
|
135
|
+
baseURL: "https://api.example.com",
|
|
136
|
+
headers: { "token_abc": "askfjshdfjk" },
|
|
137
|
+
});
|
|
138
|
+
// β Every request: token_abc: askfjshdfjk
|
|
69
139
|
|
|
70
|
-
|
|
71
|
-
|
|
140
|
+
// Multiple custom headers
|
|
141
|
+
setupApi({
|
|
142
|
+
baseURL: "https://api.example.com",
|
|
143
|
+
headers: {
|
|
144
|
+
"X-Api-Key": "your-api-key",
|
|
145
|
+
"X-App-ID": "my-app-001",
|
|
146
|
+
"Accept-Language": "en",
|
|
72
147
|
},
|
|
148
|
+
});
|
|
73
149
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
150
|
+
// Custom header + Bearer token together
|
|
151
|
+
setupApi({
|
|
152
|
+
baseURL: "https://api.example.com",
|
|
153
|
+
tokenType: "Bearer",
|
|
154
|
+
getToken: () => localStorage.getItem("token"),
|
|
155
|
+
headers: {
|
|
156
|
+
"X-Api-Key": "your-api-key", // static
|
|
77
157
|
},
|
|
78
158
|
});
|
|
159
|
+
// Both headers sent on every request
|
|
79
160
|
```
|
|
80
161
|
|
|
81
162
|
---
|
|
82
163
|
|
|
83
|
-
##
|
|
164
|
+
## πͺ Hooks
|
|
165
|
+
|
|
166
|
+
### `useApiQuery` β Fetch data (GET)
|
|
84
167
|
|
|
85
|
-
|
|
168
|
+
```ts
|
|
169
|
+
const { data, isLoading, isError, refetch } = useApiQuery(
|
|
170
|
+
queryKey, // unique cache key array
|
|
171
|
+
method, // "GET" only for queries
|
|
172
|
+
endpoint, // API path
|
|
173
|
+
params?, // query string params (optional)
|
|
174
|
+
options? // TanStack Query options (optional)
|
|
175
|
+
);
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
**Examples:**
|
|
86
179
|
|
|
87
|
-
|
|
180
|
+
```tsx
|
|
181
|
+
// Basic GET
|
|
182
|
+
const { data, isLoading } = useApiQuery(["users"], "GET", "/users");
|
|
183
|
+
|
|
184
|
+
// GET with query params β /users?page=1&limit=10
|
|
185
|
+
const { data } = useApiQuery(["users", 1], "GET", "/users", { page: 1, limit: 10 });
|
|
186
|
+
|
|
187
|
+
// GET with TanStack options
|
|
188
|
+
const { data } = useApiQuery(["user", id], "GET", `/users/${id}`, undefined, {
|
|
189
|
+
enabled: !!id, // only fetch when id exists
|
|
190
|
+
staleTime: 1000 * 60, // cache for 1 minute
|
|
191
|
+
retry: 2, // retry twice on failure
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
// Usage in component
|
|
195
|
+
function UserList() {
|
|
196
|
+
const { data, isLoading, isError } = useApiQuery(["users"], "GET", "/users");
|
|
197
|
+
|
|
198
|
+
if (isLoading) return <p>Loading...</p>;
|
|
199
|
+
if (isError) return <p>Error!</p>;
|
|
200
|
+
return <ul>{data?.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
|
|
201
|
+
}
|
|
202
|
+
```
|
|
88
203
|
|
|
89
204
|
---
|
|
90
205
|
|
|
91
|
-
|
|
206
|
+
### `useApiMutation` β Create / Update / Delete
|
|
92
207
|
|
|
93
|
-
|
|
208
|
+
```ts
|
|
209
|
+
const { mutate, mutateAsync, isPending, isError } = useApiMutation(
|
|
210
|
+
mutationKey, // unique key array
|
|
211
|
+
method, // "POST" | "PUT" | "PATCH" | "DELETE" | "GET"
|
|
212
|
+
invalidateKey? // query keys to refetch after success (optional)
|
|
213
|
+
);
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Call `mutate` with `{ endpoint, data }`:
|
|
94
217
|
|
|
95
218
|
```ts
|
|
96
|
-
|
|
219
|
+
mutate({ endpoint: "/endpoint", data: { ...payload } });
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
**Examples:**
|
|
97
223
|
|
|
98
|
-
|
|
224
|
+
#### POST β Create
|
|
225
|
+
|
|
226
|
+
```tsx
|
|
227
|
+
const { mutate, isPending } = useApiMutation(
|
|
228
|
+
["createUser"],
|
|
229
|
+
"POST",
|
|
230
|
+
["users"] // refetches ["users"] query on success
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
const handleCreate = () => {
|
|
234
|
+
mutate({
|
|
235
|
+
endpoint: "/users",
|
|
236
|
+
data: { name: "John", email: "john@example.com" },
|
|
237
|
+
});
|
|
238
|
+
};
|
|
99
239
|
```
|
|
100
240
|
|
|
101
|
-
|
|
241
|
+
#### PUT β Full Replace
|
|
242
|
+
|
|
243
|
+
```tsx
|
|
244
|
+
const { mutate } = useApiMutation(["replaceUser"], "PUT", ["users"]);
|
|
102
245
|
|
|
103
|
-
|
|
104
|
-
|
|
246
|
+
mutate({
|
|
247
|
+
endpoint: `/users/${id}`,
|
|
248
|
+
data: { name: "John", email: "john@example.com", role: "admin" },
|
|
249
|
+
});
|
|
250
|
+
```
|
|
105
251
|
|
|
106
|
-
|
|
252
|
+
#### PATCH β Partial Update
|
|
107
253
|
|
|
108
|
-
```
|
|
109
|
-
|
|
254
|
+
```tsx
|
|
255
|
+
const { mutate } = useApiMutation(["updateUser"], "PATCH", ["users"]);
|
|
110
256
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
"
|
|
114
|
-
|
|
257
|
+
mutate({
|
|
258
|
+
endpoint: `/users/${id}`,
|
|
259
|
+
data: { name: "Updated Name" },
|
|
260
|
+
});
|
|
261
|
+
```
|
|
115
262
|
|
|
116
|
-
|
|
117
|
-
const { mutate, isPending } = useApiMutation(["GET KEY"], "GET", "/users", [
|
|
118
|
-
"Validate",
|
|
119
|
-
]);
|
|
263
|
+
#### DELETE β Remove
|
|
120
264
|
|
|
121
|
-
|
|
122
|
-
const { mutate
|
|
123
|
-
"Validate",
|
|
124
|
-
]);
|
|
265
|
+
```tsx
|
|
266
|
+
const { mutate } = useApiMutation(["deleteUser"], "DELETE", ["users"]);
|
|
125
267
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
268
|
+
mutate({ endpoint: `/users/${id}` });
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
#### With callbacks
|
|
272
|
+
|
|
273
|
+
```tsx
|
|
274
|
+
const { mutate } = useApiMutation(["createUser"], "POST", ["users"]);
|
|
275
|
+
|
|
276
|
+
mutate(
|
|
277
|
+
{ endpoint: "/users", data: { name: "John" } },
|
|
278
|
+
{
|
|
279
|
+
onSuccess: (data) => toast.success("User created!"),
|
|
280
|
+
onError: (err) => toast.error("Failed to create user"),
|
|
281
|
+
}
|
|
132
282
|
);
|
|
133
283
|
```
|
|
284
|
+
|
|
285
|
+
#### Using `mutateAsync` (await)
|
|
286
|
+
|
|
287
|
+
```tsx
|
|
288
|
+
const { mutateAsync, isPending } = useApiMutation(["createUser"], "POST");
|
|
289
|
+
|
|
290
|
+
const handleSubmit = async (formData) => {
|
|
291
|
+
try {
|
|
292
|
+
const result = await mutateAsync({ endpoint: "/users", data: formData });
|
|
293
|
+
console.log("Created:", result);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
console.error(err);
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
### `api` β Direct Axios Instance
|
|
303
|
+
|
|
304
|
+
For cases where you need full control:
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
import { api } from "react-api-kit";
|
|
308
|
+
|
|
309
|
+
// GET
|
|
310
|
+
const users = await api.get("/users").then(res => res.data);
|
|
311
|
+
|
|
312
|
+
// GET with params
|
|
313
|
+
const res = await api.get("/orders", { params: { status: "pending" } });
|
|
314
|
+
|
|
315
|
+
// POST
|
|
316
|
+
const res = await api.post("/users", { name: "John" });
|
|
317
|
+
|
|
318
|
+
// PUT
|
|
319
|
+
const res = await api.put(`/users/${id}`, { name: "John", email: "john@example.com" });
|
|
320
|
+
|
|
321
|
+
// PATCH
|
|
322
|
+
const res = await api.patch(`/users/${id}`, { name: "Updated" });
|
|
323
|
+
|
|
324
|
+
// DELETE
|
|
325
|
+
const res = await api.delete(`/users/${id}`);
|
|
326
|
+
|
|
327
|
+
// Custom header for a single request only
|
|
328
|
+
const res = await api.get("/report", {
|
|
329
|
+
headers: { "X-Export-Format": "pdf" },
|
|
330
|
+
});
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
> All requests made via `api` also get the global auth header and custom headers automatically.
|
|
334
|
+
|
|
335
|
+
---
|
|
336
|
+
|
|
337
|
+
## β οΈ Error Handling
|
|
338
|
+
|
|
339
|
+
Errors are handled automatically via the response interceptor with a **4-level priority**:
|
|
340
|
+
|
|
341
|
+
| Priority | Source |
|
|
342
|
+
|----------|--------|
|
|
343
|
+
| 1οΈβ£ | `error.response.data.message` from backend |
|
|
344
|
+
| 2οΈβ£ | Your custom `errorMessages[status]` in `setupApi` |
|
|
345
|
+
| 3οΈβ£ | Built-in default messages (see table below) |
|
|
346
|
+
| 4οΈβ£ | Fallback: `error.message` or `"Network Error"` |
|
|
347
|
+
|
|
348
|
+
**Built-in default status messages:**
|
|
349
|
+
|
|
350
|
+
| Status | Default Message |
|
|
351
|
+
|--------|----------------|
|
|
352
|
+
| `400` | Bad request. Please check your input. |
|
|
353
|
+
| `401` | Session expired. Please login again. *(+ auto logout)* |
|
|
354
|
+
| `403` | You do not have permission to perform this action. |
|
|
355
|
+
| `404` | Requested resource not found. |
|
|
356
|
+
| `409` | Conflict occurred. Please try again. |
|
|
357
|
+
| `422` | Validation error. Please check the form. |
|
|
358
|
+
| `500` | Server error. Please try again later. |
|
|
359
|
+
|
|
360
|
+
> **401 Auto Logout:** When a `401` response is received, `onLogout()` is called automatically.
|
|
361
|
+
|
|
362
|
+
---
|
|
363
|
+
|
|
364
|
+
## π Package Structure
|
|
365
|
+
|
|
366
|
+
```
|
|
367
|
+
src/
|
|
368
|
+
βββ config.ts β ApiConfig interface + setupApi()
|
|
369
|
+
βββ index.ts β Public exports
|
|
370
|
+
βββ api/
|
|
371
|
+
β βββ axios.ts β Axios instance + request interceptor (auth + headers)
|
|
372
|
+
β βββ interceptors.ts β Response interceptor (error handling + auto logout)
|
|
373
|
+
β βββ globalApi.ts β GET / POST / PUT / PATCH / DELETE wrappers
|
|
374
|
+
βββ hooks/
|
|
375
|
+
βββ useApiQuery.ts β useQuery wrapper
|
|
376
|
+
βββ useApiMutation.ts β useMutation wrapper
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
---
|
|
380
|
+
|
|
381
|
+
## π Exports
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
import {
|
|
385
|
+
setupApi, // configure baseURL, token, headers, toast, etc.
|
|
386
|
+
api, // raw Axios instance (with interceptors)
|
|
387
|
+
useApiQuery, // TanStack Query hook for GET
|
|
388
|
+
useApiMutation, // TanStack Query hook for POST / PATCH / DELETE
|
|
389
|
+
} from "react-api-kit";
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
---
|
|
393
|
+
|
|
394
|
+
## π License
|
|
395
|
+
|
|
396
|
+
ISC Β© [Ajay Kammar](https://github.com/)
|
package/dist/react-api-kit.mjs
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
import c from "axios";
|
|
2
|
-
import { useQuery as p, useQueryClient as d, useMutation as
|
|
3
|
-
let
|
|
2
|
+
import { useQuery as p, useQueryClient as d, useMutation as h } from "@tanstack/react-query";
|
|
3
|
+
let r;
|
|
4
4
|
const m = (e) => {
|
|
5
|
-
|
|
6
|
-
},
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
5
|
+
r = e;
|
|
6
|
+
}, a = c.create();
|
|
7
|
+
a.interceptors.request.use((e) => {
|
|
8
|
+
r?.baseURL && (e.baseURL = r.baseURL), r?.headers && Object.entries(r.headers).forEach(([s, o]) => {
|
|
9
|
+
e.headers[s] = o;
|
|
10
|
+
});
|
|
11
|
+
const t = r?.getToken?.();
|
|
12
|
+
if (t) {
|
|
13
|
+
const s = r?.tokenType ?? "Bearer";
|
|
14
|
+
e.headers.Authorization = `${s} ${t}`;
|
|
15
|
+
}
|
|
16
|
+
return e;
|
|
11
17
|
});
|
|
12
|
-
|
|
13
|
-
(e) => (
|
|
18
|
+
a.interceptors.response.use(
|
|
19
|
+
(e) => (r?.onSuccess?.(e.data), e),
|
|
14
20
|
(e) => {
|
|
15
21
|
const t = e?.response?.status, s = {
|
|
16
22
|
400: "Bad request. Please check your input.",
|
|
@@ -20,36 +26,37 @@ n.interceptors.response.use(
|
|
|
20
26
|
409: "Conflict occurred. Please try again.",
|
|
21
27
|
422: "Validation error. Please check the form.",
|
|
22
28
|
500: "Server error. Please try again later."
|
|
23
|
-
},
|
|
24
|
-
return
|
|
29
|
+
}, o = e?.response?.data?.message || t && r?.errorMessages?.[t] || t && s[t] || e?.message || "Network Error";
|
|
30
|
+
return r?.toast?.error(o, r.toastOptions), r?.onError?.(e, o), t === 401 && r?.onLogout?.(), Promise.reject(e);
|
|
25
31
|
}
|
|
26
32
|
);
|
|
27
33
|
const u = {
|
|
28
|
-
GET: (e, t) =>
|
|
29
|
-
POST: (e, t) =>
|
|
30
|
-
|
|
31
|
-
|
|
34
|
+
GET: (e, t) => a.get(e, { params: t }).then((s) => s.data),
|
|
35
|
+
POST: (e, t) => a.post(e, t).then((s) => s.data),
|
|
36
|
+
PUT: (e, t) => a.put(e, t).then((s) => s.data),
|
|
37
|
+
PATCH: (e, t) => a.patch(e, t).then((s) => s.data),
|
|
38
|
+
DELETE: (e) => a.delete(e).then((t) => t.data)
|
|
32
39
|
};
|
|
33
|
-
function
|
|
40
|
+
function y(e, t, s, o, n) {
|
|
34
41
|
return p({
|
|
35
42
|
queryKey: e,
|
|
36
|
-
queryFn: () => u[t](s,
|
|
37
|
-
...
|
|
43
|
+
queryFn: () => u[t](s, o),
|
|
44
|
+
...n
|
|
38
45
|
});
|
|
39
46
|
}
|
|
40
|
-
function
|
|
41
|
-
const
|
|
42
|
-
return
|
|
47
|
+
function g(e, t, s) {
|
|
48
|
+
const o = d();
|
|
49
|
+
return h({
|
|
43
50
|
mutationKey: e,
|
|
44
|
-
mutationFn: ({ endpoint:
|
|
51
|
+
mutationFn: ({ endpoint: n, data: i }) => u[t](n, i),
|
|
45
52
|
onSuccess: () => {
|
|
46
|
-
s &&
|
|
53
|
+
s && o.invalidateQueries({ queryKey: s });
|
|
47
54
|
}
|
|
48
55
|
});
|
|
49
56
|
}
|
|
50
57
|
export {
|
|
51
|
-
|
|
58
|
+
a as api,
|
|
52
59
|
m as setupApi,
|
|
53
|
-
|
|
54
|
-
|
|
60
|
+
g as useApiMutation,
|
|
61
|
+
y as useApiQuery
|
|
55
62
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(a,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("axios"),require("@tanstack/react-query")):typeof define=="function"&&define.amd?define(["exports","axios","@tanstack/react-query"],i):(a=typeof globalThis<"u"?globalThis:a||self,i(a.ReactApiKit={},a.axios,a.reactQuery))})(this,(function(a,i,u){"use strict";let n;const p=e=>{n=e},o=i.create();o.interceptors.request.use(e=>{n?.baseURL&&(e.baseURL=n.baseURL),n?.headers&&Object.entries(n.headers).forEach(([s,r])=>{e.headers[s]=r});const t=n?.getToken?.();if(t){const s=n?.tokenType??"Bearer";e.headers.Authorization=`${s} ${t}`}return e}),o.interceptors.response.use(e=>(n?.onSuccess?.(e.data),e),e=>{const t=e?.response?.status,s={400:"Bad request. Please check your input.",401:"Session expired. Please login again.",403:"You do not have permission to perform this action.",404:"Requested resource not found.",409:"Conflict occurred. Please try again.",422:"Validation error. Please check the form.",500:"Server error. Please try again later."},r=e?.response?.data?.message||t&&n?.errorMessages?.[t]||t&&s[t]||e?.message||"Network Error";return n?.toast?.error(r,n.toastOptions),n?.onError?.(e,r),t===401&&n?.onLogout?.(),Promise.reject(e)});const d={GET:(e,t)=>o.get(e,{params:t}).then(s=>s.data),POST:(e,t)=>o.post(e,t).then(s=>s.data),PUT:(e,t)=>o.put(e,t).then(s=>s.data),PATCH:(e,t)=>o.patch(e,t).then(s=>s.data),DELETE:e=>o.delete(e).then(t=>t.data)};function f(e,t,s,r,c){return u.useQuery({queryKey:e,queryFn:()=>d[t](s,r),...c})}function h(e,t,s){const r=u.useQueryClient();return u.useMutation({mutationKey:e,mutationFn:({endpoint:c,data:l})=>d[t](c,l),onSuccess:()=>{s&&r.invalidateQueries({queryKey:s})}})}a.api=o,a.setupApi=p,a.useApiMutation=h,a.useApiQuery=f,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})}));
|
package/package.json
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-api-kit",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"description": "Reusable Axios + TanStack Query API hooks for React",
|
|
5
5
|
"license": "ISC",
|
|
6
6
|
"author": "Ajay kammar",
|
|
7
|
-
|
|
8
7
|
"main": "./dist/react-api-kit.umd.js",
|
|
9
8
|
"module": "./dist/react-api-kit.mjs",
|
|
10
9
|
"types": "./dist/index.d.ts",
|