@teamkeel/client-react 0.365.5 → 0.365.7

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 (2) hide show
  1. package/package.json +3 -2
  2. package/src/index.tsx +65 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamkeel/client-react",
3
- "version": "0.365.5",
3
+ "version": "0.365.7",
4
4
  "description": "React helpers for Keel clients",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -22,6 +22,7 @@
22
22
  "typescript": "5.1.6"
23
23
  },
24
24
  "files": [
25
- "dist"
25
+ "dist",
26
+ "src"
26
27
  ]
27
28
  }
package/src/index.tsx ADDED
@@ -0,0 +1,65 @@
1
+ import React, { createContext, useContext, useEffect, useRef } from "react";
2
+
3
+ interface KeelContextType<T> {
4
+ client: T;
5
+ }
6
+
7
+ const KeelContext = createContext<KeelContextType<any>>({
8
+ client: null,
9
+ });
10
+
11
+ interface KeelProviderProps<
12
+ T extends new (...args: any[]) => any,
13
+ U = Omit<ConstructorParameters<T>[0], "endpoint">
14
+ > {
15
+ /**
16
+ * The base URL for the client.
17
+ */
18
+ baseUrl: string;
19
+ /**
20
+ * Additional config options for the client.
21
+ */
22
+ config?: U;
23
+ children: React.ReactNode;
24
+ }
25
+
26
+ export const keel = <T extends new (...args: any[]) => any>(Client: T) => {
27
+ function KeelProvider<T extends new (...args: any[]) => any>({
28
+ baseUrl,
29
+ config,
30
+ children,
31
+ }: KeelProviderProps<T>) {
32
+ if (typeof Client !== "function") {
33
+ throw new Error("Client must be a Keel class");
34
+ }
35
+
36
+ const clientConstructor = Client as new (args: any) => any;
37
+ const clientArgs = { baseUrl, ...config };
38
+ const clientRef = useRef(new clientConstructor(clientArgs));
39
+
40
+ const client = clientRef.current;
41
+
42
+ useEffect(() => {
43
+ client.client.setBaseUrl(baseUrl);
44
+ }, [baseUrl, client]);
45
+
46
+ return (
47
+ <KeelContext.Provider value={{ client }}>{children}</KeelContext.Provider>
48
+ );
49
+ }
50
+
51
+ return {
52
+ KeelProvider: KeelProvider<T>,
53
+ useKeel: useKeel<T>,
54
+ };
55
+ };
56
+
57
+ function useKeel<T extends new (...args: any) => any>() {
58
+ const keelContext = useContext<KeelContextType<InstanceType<T>>>(KeelContext);
59
+
60
+ if (!keelContext) {
61
+ throw new Error("useKeel must be used within a KeelProvider");
62
+ }
63
+
64
+ return keelContext.client;
65
+ }