PluginProbe
HubSpot All-In-One Marketing – Forms, Popups, Live Chat / 11.3.71
HubSpot All-In-One Marketing – Forms, Popups, Live Chat v11.3.71
11.3.75 11.3.73 11.3.71 11.3.70 11.3.69 11.3.64 11.3.65 11.3.62 11.3.61 11.3.56 11.3.58 11.0.31 11.0.52 11.0.54 11.0.56 11.0.58 11.0.7 11.1.10 11.1.11 11.1.13 11.1.14 11.1.15 11.1.2 11.1.20 11.1.21 All 73 releases
leadin / scripts / utils / useGetEmbedder.ts

useGetEmbedder.ts in HubSpot All-In-One Marketing – Forms, Popups, Live Chat 11.3.71, at scripts/utils/useGetEmbedder.ts

68 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import React from 'react';
2 import { useEffect, useState } from 'react';
3 import { __ } from '@wordpress/i18n';
4 import { fetchAccessToken } from '../api/wordpressApiClient';
5 import { getOrCreateBackgroundApp } from './backgroundAppUtils';
6 import { isRefreshTokenAvailable } from './isRefreshTokenAvailable';
7 import ErrorHandler from '../shared/Common/ErrorHandler';
8
9 export function useGetEmbedder() {
10 const [embedder, setEmbedder] = useState<any>(null);
11 const [errorStatus, setErrorStatus] = useState<number | null>(null);
12
13 const loadEmbedder = () => {
14 fetchAccessToken()
15 .then(
16 ({
17 accessToken,
18 expiresIn,
19 }: {
20 accessToken: string;
21 expiresIn: number;
22 }) => {
23 const app = getOrCreateBackgroundApp(accessToken, expiresIn);
24 if (app) {
25 setEmbedder(app);
26 } else {
27 // Embedder script failed to load — surface the error UI instead
28 // of leaving the caller stuck in a loading state.
29 setErrorStatus(500);
30 }
31 }
32 )
33 .catch((err: any) => setErrorStatus((err && err.status) || 500));
34 };
35
36 useEffect(() => {
37 if (isRefreshTokenAvailable()) {
38 loadEmbedder();
39 }
40 }, []);
41
42 const errorElement =
43 errorStatus !== null
44 ? React.createElement(ErrorHandler, {
45 status: errorStatus,
46 resetErrorState: () => {
47 setErrorStatus(null);
48 loadEmbedder();
49 },
50 errorInfo: {
51 header: __('Unable to load HubSpot', 'leadin'),
52 message: __(
53 'There was a problem connecting to HubSpot. Please try again.',
54 'leadin'
55 ),
56 action: __('Retry', 'leadin'),
57 },
58 })
59 : null;
60
61 return {
62 embedder,
63 errorElement,
64 isLoading:
65 isRefreshTokenAvailable() && embedder === null && errorStatus === null,
66 };
67 }
68