Removing an item from the shopping cart

Let's take a look at the handleRemoveFromCartButtonClickEvent function, which gets called when the Remove From Cart button is clicked:

func handleRemoveFromCartButtonClickEvent(env *common.Env, event dom.Event) {
productSKU := event.Target().GetAttribute("data-sku")
go removeFromCart(env, productSKU)
}

In this function, we obtain the product SKU code from the event target element's data-sku attribute. We then call the removeFromCart function as a goroutine, passing in the env object and productSKU.

Here is the source listing of the removeFromCart function:

func removeFromCart(env *common.Env, productSKU string) {

m := make(map[string]string)
m["productSKU"] = productSKU
jsonData, _ := json.Marshal(m)

data, err := xhr.Send("DELETE", "/restapi/remove-item-from-cart", jsonData)
if err != nil {
println("Encountered error: ", err)
notify.Error("Failed to remove item from cart!")
return
}
var products []*models.Product
json.NewDecoder(strings.NewReader(string(data))).Decode(&products)
renderShoppingCartItems(env)
notify.Success("Item removed from cart")
}

We create a new map, m, in the removeFromCart function, which is used to house productSKU. We can access the product's SKU value from the  m map by providing the "productSKU" key. We have intended to send this map to the web server through the request body. The reason that we have chosen the map type, as opposed to simply sending the product's SKU string value, is that we want to make our solution extensible. In the future, if there is any additional information that should be sent to the server, we can include that value as part of an additional key-value pair in the map.

We encode the map into its JSON representation and make an XHR call to the web server, sending the map JSON data. Finally, we make a call to the renderShoppingCartItems function to render the shopping cart items. Remember that by calling this function, we will be performing an XHR call to get the latest products in the shopping cart (which represents the current state of the shopping cart). This ensures that we will have the most up-to-date state of the shopping cart, since again, we are using the server-side session (where the shopping cart state is stored) as our single source of truth.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.84.169