Search code examples
javascriptarrayssessioncartsvelte

req.session.cart [object object] [object object] how to iterate and view it in my sapper/svelte application


night owls: So I'm practicing my sapper/svelte application. Created a shopping page with few items where I can order those items and add them to my shopping cart.

Everything is working (I add items to the cart in the session) but the items I add are stored in the session (db session) as [object object] [object object] and I don't know how to view that despite the fact I know how the object is designed. I read all the tuts out there on how to iterate over an object and all that, yet, I'm unable to display the req.session.cart objects in my application. I don't know if I'm doing it right or wrong. Please advise.

my svelte page with the shopping items are basic and no need to add it here. Here is my server route where I capture the ordered item and process those entries.

SC3.JS file where I fetch the data:

    var fetch = require('node-fetch');

export async function post(req, res, next) {

    res.setHeader('Content-Type', 'application/json');
    /* Retrieve the data */
    var data = req.body;

    //cart constructor
    function Cart() {        

        this.add = function (item) {            
            this.item = item;
            let title = this.item.title;
            let price = this.item.price;


            let storeditem = { title: title, price: price };
            req.session.cart += { item: storeditem };
            console.log("session log: ", req.session.cart);     

        }; 
    }

    var cart = new Cart();
    cart.add(data);


    /* Returns the result */
    return res.end(JSON.stringify({ info: data }));

}

my mongodb is showing the followingenter image description here

Am I adding the items wrong by doing req.session.cart += storeditem ??? If this is the right way to store the items, how do I retrieve them with [object object] nested inside the session cart object?

I tried obj.keys, obj.values etc from the es6 new object methods but it all it showed was some keys but not the actual items (title and price) that I added to the cart.

This is a sapper/svelte app which is pure html, css and js Any help would be appreciated.


Solution

  • You are adding the items wrong, you cannot += an object. (this will cast it to string)

    Here we can reproduce your bug:

    let cart = {};
    let storeditem = { title: 'my title', price: 1.23 };
    
    cart += { item: storeditem };
    
    console.log("session log: ", cart); 

    And here is how we can fix that:

    let cart = {};
    let storeditem = { title: 'my title', price: 1.23 };
    let id = 'you need an id'; // Maybe you can use item.id ???
    cart[id] = { item: storeditem };
    
    console.log("session log: ", cart);