-
Notifications
You must be signed in to change notification settings - Fork 55
/
AppBridgeProvider.jsx
92 lines (84 loc) · 2.76 KB
/
AppBridgeProvider.jsx
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
import { useMemo, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Provider } from "@shopify/app-bridge-react";
import { Banner, Layout, Page } from "@shopify/polaris";
/**
* A component to configure App Bridge.
* @desc A thin wrapper around AppBridgeProvider that provides the following capabilities:
*
* 1. Ensures that navigating inside the app updates the host URL.
* 2. Configures the App Bridge Provider, which unlocks functionality provided by the host.
*
* See: https://shopify.dev/apps/tools/app-bridge/getting-started/using-react
*/
export function AppBridgeProvider({ children }) {
const location = useLocation();
const navigate = useNavigate();
const history = useMemo(
() => ({
replace: (path) => {
navigate(path, { replace: true });
},
}),
[navigate]
);
const routerConfig = useMemo(
() => ({ history, location }),
[history, location]
);
// The host may be present initially, but later removed by navigation.
// By caching this in state, we ensure that the host is never lost.
// During the lifecycle of an app, these values should never be updated anyway.
// Using state in this way is preferable to useMemo.
// See: https://stackoverflow.com/questions/60482318/version-of-usememo-for-caching-a-value-that-will-never-change
const [appBridgeConfig] = useState(() => {
const host =
new URLSearchParams(location.search).get("host") ||
window.__SHOPIFY_DEV_HOST;
window.__SHOPIFY_DEV_HOST = host;
return {
host,
apiKey: process.env.SHOPIFY_API_KEY,
forceRedirect: true,
};
});
if (!process.env.SHOPIFY_API_KEY || !appBridgeConfig.host) {
const bannerProps = !process.env.SHOPIFY_API_KEY
? {
title: "Missing Shopify API Key",
children: (
<>
Your app is running without the SHOPIFY_API_KEY environment
variable. Please ensure that it is set when running or building
your React app.
</>
),
}
: {
title: "Missing host query argument",
children: (
<>
Your app can only load if the URL has a <b>host</b> argument.
Please ensure that it is set, or access your app using the
Partners Dashboard <b>Test your app</b> feature
</>
),
};
return (
<Page narrowWidth>
<Layout>
<Layout.Section>
<div style={{ marginTop: "100px" }}>
<Banner {...bannerProps} status="critical" />
</div>
</Layout.Section>
</Layout>
</Page>
);
}
return (
<Provider config={appBridgeConfig} router={routerConfig}>
{children}
</Provider>
);
}