I have a cartHelper:
let cartHelper = {
cartCookieName: "_cart",
getCart: function (callback = undefined) {
return apiHelper.getRequest(
"/carts",
(response) => {
document.cookie = `${this.cartCookieName}=${response.data.attributes.cart_guid};`;
if (callback) { callback(); }
},
)
},
}
I want to call getCart function if "_cart" is empty. Can you help me with how I can make this check? More clearly, getCart function is being called when the button is clicked. And I am making and API call to get the cart_guid and I am storing in cookie. What I am trying to do if cart_guid is already in the cookie, I dont want to do anything but if it is not I want to create the cookie with cartguid.
Thanks for your helps.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style></style>
</head>
<body>
<button onclick="checkCookie()">Check Cookie</button>
<p>Click btn to check cookie..!</p>
</body>
<script>
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function checkCookie() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
console.log(
"%ccookie is null",
"color:white;background: red;padding: 2px 10px;"
);
} else {
console.log(
"%ccookie is not null",
"color:white;background: red;padding: 2px 10px;"
);
}
}
</script>
</html>