generated from graasp/graasp-repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
withToken.tsx
108 lines (90 loc) · 2.57 KB
/
withToken.tsx
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
import React, { ReactElement, createContext } from 'react';
import { UseQueryResult } from '@tanstack/react-query';
import { Token } from '../types.js';
const TokenContext = createContext<string>('');
interface WithTokenContextProps {
children: ReactElement | (ReactElement | false | null)[];
useAuthToken: (itemId: string) => UseQueryResult<Token, unknown>;
LoadingComponent?: JSX.Element;
onError?: (error: unknown) => void;
}
const WithTokenContext = ({
children,
LoadingComponent,
onError,
useAuthToken,
}: WithTokenContextProps): JSX.Element => {
const itemId = new URL(window.location.toString()).searchParams.get('itemId') || '';
if (!itemId) {
const error = 'ItemId not found in querystring parameters';
if (onError) {
onError(error);
} else {
console.error(error);
}
}
const { data: token, isLoading, isError, error } = useAuthToken(itemId);
if (token) {
return <TokenContext.Provider value={token}>{children}</TokenContext.Provider>;
}
if (isLoading) {
return LoadingComponent ?? <div>loading...</div>;
}
if (isError) {
if (onError) {
onError(error);
} else {
console.error(error);
}
}
return <div>Whoops something went wrong...</div>;
};
/**
* @deprecated
*/
interface Props {
useAuthToken: (itemId: string) => UseQueryResult<Token, unknown>;
LoadingComponent?: JSX.Element;
onError?: (error: unknown) => void;
}
/**
* @deprecated use `WithTokenContext` instead
*/
const withToken = <P extends object>(
Component: React.ComponentType<P>,
props: Props,
): ((childProps: P) => JSX.Element) => {
const WithTokenComponent = (childProps: P): JSX.Element => {
const { LoadingComponent, onError, useAuthToken } = props;
const itemId = new URL(window.location.toString()).searchParams.get('itemId') || '';
if (!itemId) {
const error = 'ItemId not found in querystring parameters';
if (onError) {
onError(error);
} else {
console.error(error);
}
}
const { data: token, isLoading, isError, error } = useAuthToken(itemId);
if (token) {
return (
<TokenContext.Provider value={token}>
<Component {...childProps} />
</TokenContext.Provider>
);
}
if (isLoading) {
return LoadingComponent ?? <div>loading...</div>;
}
if (isError) {
if (onError) {
onError(error);
} else {
console.error(error);
}
}
return <div>Whoops something went wrong...</div>;
};
return WithTokenComponent;
};
export { TokenContext, WithTokenContext, withToken };