Commit 6de9ff3d authored by Christophe Benz's avatar Christophe Benz

Fix cart when never defined

parent 4d0b0b6e
......@@ -24,18 +24,26 @@ var rAF =
}, 0)
}
function parseSeriesTuplesJson(seriesIdsJson) {
function parseSeriesTuples(seriesTuplesStr) {
try {
return JSON.parse(seriesIdsJson)
return JSON.parse(seriesTuplesStr)
} catch (error) {
console.error("Error parsing cart in localStorage, resetting cart:", error)
var newSeriesIds = []
window.localStorage.setItem(cartStorageKey, JSON.stringify(newSeriesIds))
return newSeriesIds
var newSeriesTuples = []
setCart(newSeriesTuples)
return newSeriesTuples
}
}
var initialCartSeriesTuples = parseSeriesTuplesJson(window.localStorage.getItem("cart"))
function getCart() {
return parseSeriesTuples(window.localStorage.getItem(cartStorageKey) || [])
}
function setCart(cartSeriesTuples) {
window.localStorage.setItem(cartStorageKey, JSON.stringify(cartSeriesTuples))
}
var initialCartSeriesTuples = getCart()
var flags = Object.assign({}, config, { cartSeriesTuples: initialCartSeriesTuples })
var app = Elm.Main.embed(document.getElementById("main"), flags)
......@@ -64,8 +72,8 @@ function closeAllDetailElements() {
}
function addToCart(seriesTuple) {
var cartSeriesTuples = parseSeriesTuplesJson(window.localStorage.getItem("cart")).concat([seriesTuple])
window.localStorage.setItem(cartStorageKey, JSON.stringify(cartSeriesTuples))
var cartSeriesTuples = getCart().concat([seriesTuple])
setCart(cartSeriesTuples)
app.ports.infoForElm.send({ tag: "CartChanged", data: cartSeriesTuples })
}
......@@ -73,10 +81,10 @@ function removeFromCart(seriesId) {
function tripletEquals(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]
}
var cartSeriesTuples = parseSeriesTuplesJson(window.localStorage.getItem("cart")).filter(function(seriesTuple1) {
var cartSeriesTuples = getCart().filter(function(seriesTuple1) {
return !tripletEquals(seriesTuple1[0], seriesId)
})
window.localStorage.setItem(cartStorageKey, JSON.stringify(cartSeriesTuples))
setCart(cartSeriesTuples)
app.ports.infoForElm.send({ tag: "CartChanged", data: cartSeriesTuples })
}
......@@ -87,7 +95,7 @@ function clearCart(withConfirmation) {
}
}
var cartSeriesTuples = []
window.localStorage.setItem(cartStorageKey, JSON.stringify(cartSeriesTuples))
setCart(cartSeriesTuples)
app.ports.infoForElm.send({ tag: "CartChanged", data: cartSeriesTuples })
}
......@@ -257,6 +265,6 @@ app.ports.infoForOutside.subscribe(function(msg) {
})
window.addEventListener("storage", function(event) {
var cartSeriesTuples = parseSeriesTuplesJson(event.newValue)
var cartSeriesTuples = parseSeriesTuples(event.newValue)
app.ports.infoForElm.send({ tag: "CartChanged", data: cartSeriesTuples })
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment