-
Notifications
You must be signed in to change notification settings - Fork 54
/
ProductsCard.jsx
81 lines (75 loc) · 2.04 KB
/
ProductsCard.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
import { useState } from "react";
import {
Card,
Heading,
TextContainer,
DisplayText,
TextStyle,
} from "@shopify/polaris";
import { Toast } from "@shopify/app-bridge-react";
import { useAppQuery, useAuthenticatedFetch } from "../hooks";
export function ProductsCard() {
const emptyToastProps = { content: null };
const [isLoading, setIsLoading] = useState(true);
const [toastProps, setToastProps] = useState(emptyToastProps);
const fetch = useAuthenticatedFetch();
const {
data,
refetch: refetchProductCount,
isLoading: isLoadingCount,
isRefetching: isRefetchingCount,
} = useAppQuery({
url: "/api/products/count",
reactQueryOptions: {
onSuccess: () => {
setIsLoading(false);
},
},
});
const toastMarkup = toastProps.content && !isRefetchingCount && (
<Toast {...toastProps} onDismiss={() => setToastProps(emptyToastProps)} />
);
const handlePopulate = async () => {
setIsLoading(true);
const response = await fetch("/api/products/create");
if (response.ok) {
await refetchProductCount();
setToastProps({ content: "5 products created!" });
} else {
setIsLoading(false);
setToastProps({
content: "There was an error creating products",
error: true,
});
}
};
return (
<>
{toastMarkup}
<Card
title="Product Counter"
sectioned
primaryFooterAction={{
content: "Populate 5 products",
onAction: handlePopulate,
loading: isLoading,
}}
>
<TextContainer spacing="loose">
<p>
Sample products are created with a default title and price. You can
remove them at any time.
</p>
<Heading element="h4">
TOTAL PRODUCTS
<DisplayText size="medium">
<TextStyle variation="strong">
{isLoadingCount ? "-" : data.count}
</TextStyle>
</DisplayText>
</Heading>
</TextContainer>
</Card>
</>
);
}