forked from PrestaShop/hummingbird
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUseHandleCartAction.ts
More file actions
76 lines (62 loc) · 2.15 KB
/
UseHandleCartAction.ts
File metadata and controls
76 lines (62 loc) · 2.15 KB
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
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import SelectorsMap from '@constants/selectors-map';
import useAlert from './useAlert';
const handleCartAction = (event: Event): void => {
event.stopPropagation();
event.preventDefault();
// Get the target element and its dataset
const target = event.target as HTMLElement;
// Make request to refresh the cart
sendCartRefreshRequest(target);
};
const sendCartRefreshRequest = (target: HTMLElement): void => {
const {prestashop, Theme: {events}} = window;
const {dataset} = target;
const targetUrl = target.getAttribute('href');
if (targetUrl === null) {
return;
}
const formData = new FormData();
formData.append('ajax', '1');
formData.append('action', 'update');
fetch(targetUrl, {
method: 'POST',
body: formData,
})
.then((resp: Response) => {
// Refresh cart preview
prestashop.emit(events.updateCart, {
reason: dataset,
resp,
});
// Show product removal success alert
if (target && target.getAttribute('data-link-action') === SelectorsMap.cart.deleteLinkAction) {
const alertPlaceholder = document.querySelector(SelectorsMap.cart.alertPlaceholder);
const productUrl = target.getAttribute('data-product-url');
const productName = target.getAttribute('data-product-name');
if (alertPlaceholder && productUrl && productName) {
const alertText = alertPlaceholder.getAttribute('data-alert');
const productLink = `<a class="alert-link" href="${productUrl}">${productName}</a>`;
const alertMessage = `${productLink} ${alertText}`;
if (alertMessage) {
const alert = useAlert(alertMessage, {
type: 'success',
selector: SelectorsMap.cart.alertPlaceholder,
});
alert.show();
}
}
}
})
.catch((err) => {
const errorData = err as Response;
prestashop.emit(events.handleError, {
eventType: 'updateProductInCart',
errorData,
});
});
};
export default handleCartAction;