-
Notifications
You must be signed in to change notification settings - Fork 0
/
useCustomCart.ts
54 lines (48 loc) · 1.28 KB
/
useCustomCart.ts
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
import {useCart} from "@shopify/hydrogen-react";
import {useContext} from "react";
const sleepUntil = async (f: () => boolean, timeoutMs = 1000) => {
return new Promise((resolve, reject) => {
const timeWas = new Date();
const wait = setTimeout(() => setInterval(function () {
if (f()) {
clearInterval(wait);
resolve(true);
} else if (+new Date() - +timeWas > timeoutMs) {
clearInterval(wait);
reject(false);
}
}, 20), 200);
});
};
export const useCustomCart = () => {
const cart = useCart();
return {
create() {
cart.cartCreate({});
},
cart: cart,
async addProduct(productId: string) {
console.log("Attribute update")
cart.cartAttributesUpdate([{key: "shippingData", value: "abc"}]);
await sleepUntil(() => {
if (cart.status !== "idle") {
console.log("Cart status", cart.status);
}
return cart.status === "idle";
});
console.log("Lines add");
cart.linesAdd([
{
merchandiseId: productId,
quantity: 20,
},
]);
await sleepUntil(() => {
if (cart.status !== "idle") {
console.log("Cart status", cart.status);
}
return cart.status === "idle";
});
}
}
}