Skip to content

Commit 602a1e7

Browse files
committed
edit page now working too
1 parent 60f81d4 commit 602a1e7

File tree

7 files changed

+577
-11
lines changed

7 files changed

+577
-11
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ node_modules
1919

2020
## Sample Apps
2121
sample-apps/*/web/frontend/metafields.js
22+
!sample-apps/discounts/web/frontend/metafields.js
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export { useAppQuery } from "./useAppQuery";
22
export { useAuthenticatedFetch } from "./useAuthenticatedFetch";
3+
export { useDiscount } from "./useDiscount";
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { useEffect, useState } from "react";
2+
import { DiscountMethod } from "@shopify/discount-app-components";
3+
4+
import { useAuthenticatedFetch } from "./";
5+
6+
export function useDiscount(id) {
7+
const authenticatedFetch = useAuthenticatedFetch();
8+
const [discount, setDiscount] = useState(null);
9+
const [error, setError] = useState(null);
10+
const [isLoading, setIsLoading] = useState(true);
11+
12+
useEffect(() => {
13+
let isCancelled = false;
14+
15+
setIsLoading(true);
16+
setError(null);
17+
18+
authenticatedFetch(`/api/discounts/${id}`)
19+
.then((response) => response.json())
20+
.then(({ errors, data }) => {
21+
if (isCancelled) return;
22+
23+
const remoteErrors = errors || data?.discountNode?.userErrors;
24+
25+
if (remoteErrors?.length > 0) {
26+
setError(errors);
27+
return;
28+
}
29+
30+
const { discountNode } = data;
31+
32+
if (!discountNode) {
33+
setError([{ message: "Discount not found" }]);
34+
return;
35+
}
36+
37+
const {
38+
configurationField,
39+
discount: {
40+
__typename,
41+
appliesOncePerCustomer,
42+
codes,
43+
combinesWith,
44+
endsAt,
45+
startsAt,
46+
title,
47+
usageLimit,
48+
},
49+
} = discountNode;
50+
51+
const method =
52+
__typename === "DiscountAutomaticApp"
53+
? DiscountMethod.Automatic
54+
: DiscountMethod.Code;
55+
56+
setDiscount({
57+
appliesOncePerCustomer,
58+
code: codes?.nodes[0]?.code,
59+
combinesWith,
60+
configuration: JSON.parse(configurationField?.value ?? "{}"),
61+
configurationId: configurationField?.id,
62+
endsAt,
63+
id,
64+
method,
65+
startsAt,
66+
title,
67+
usageLimit,
68+
});
69+
70+
setIsLoading(false);
71+
})
72+
.catch((error) => {
73+
setError(error);
74+
setIsLoading(false);
75+
});
76+
77+
return () => {
78+
isCancelled = true;
79+
};
80+
}, [id]);
81+
82+
return {
83+
discount,
84+
isLoading,
85+
error,
86+
};
87+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export default {
2+
namespace: '$app:volume-discount',
3+
key: 'function-configuration'
4+
}

0 commit comments

Comments
 (0)