Can't render my items in to shopping cart javascript

I have two different html files and one javascript so one is for shop and other is for bag but when I click in add to cart it’s not rendering in to my cartshop file here’s my code: `const renderCart = () => {
console.log(‘Rendering cart…’);
console.log(‘selectors.cartItems:’, selectors.cartItems);
if (selectors.cartItems) {
console.log(‘Cart body exists. Rendering cart items.’);
selectors.cartItems.innerHTML = cart.map(({ id, qty }) => {
//gets products information
const product = products.find((x) => x.id === id);
const { title, image, price } = product;
const amount = price * qty;

            return `
                <div class="cart-item" data-id="${id}">
                    <img src="${image}" alt="${title}">
                    <div class="cart-item-details">
                        <h3>${title}</h3>
                        <h5>$${price}</h5>
                        <div class="cart-item-amount">
                            <i class="bi bi-dash-lg"></i>
                            <span class="qty">${qty}</span>
                            <i class="bi bi-plus-lg"></i>
                            <span class="cart-item-price">${amount}</span>
                        </div>
                    </div>
                </div>
            `;
        }).join("");
        console.log('Cart rendered successfully.');
    }
};`

Please link a minimum viable version of your code. At this present I don’t believe I have enough of your code to run it, much less begin to debug what went wrong.

1 Like
document.addEventListener("DOMContentLoaded", () => {
    let products = [];
    let cart = [];

    const selectors = {
        products: document.querySelector(".products"),
        cartItems: document.querySelector(".cart-items"),
        cart: document.querySelector(".cart"),
        cartBtn: document.querySelector(".cart-btn"),
        cartQty: document.querySelector(".cart-qty"),
        cartClear: document.querySelector(".cart-clear"),
    };

    //* Event listeners
    const setupListeners = () => {
        console.log('Setting up listeners...');
        if (selectors.products) {
            console.log('Adding click listener to products...');
            selectors.products.addEventListener('click', addToCart);
        }
    };

    //* Event handlers
    const initStore = () => {
        console.log('Initializing store...');
        loadProducts("https://fakestoreapi.com/products").then(() => {
            renderProducts();
            renderCart();
        });
    };

    const addToCart = (e) => {
        console.log('Adding to cart...');
        if (e.target.hasAttribute("data-id")) {
            const id = parseInt(e.target.dataset.id);
            const inCart = cart.find((x) => x.id === id);
            if (inCart) {
                alert('Item is already in the cart');
                return;
            }
            cart.push({ id, qty: 1 });
            renderProducts();
            renderCart();
        }
    };

    const renderProducts = () => {
        console.log('Rendering products...');
        if (selectors.products) {
            selectors.products.innerHTML = products.map((product) => {
                const { id, title, image, price } = product;
                const inCart = cart.find(x => x.id === id);
                const disabled = inCart ? "disabled" : "";
                const text = inCart ? "Added to cart" : "Add to cart";

                return `
                    <div class="product">
                        <img src="${image}" alt="${title}">
                        <h3>${title}</h3>
                        <h5>$${price}</h5>
                        <button ${disabled} data-id=${id}>${text}</button>
                    </div>
                `;
            }).join("");
        }
    };

    const renderCart = () => {
        
        console.log('selectors.cartItems:', selectors.cartItems);
        if (selectors.cartItems) {
            console.log('Cart body exists. Rendering cart items.');
            selectors.cartItems.innerHTML = cart.map(({ id, qty }) => {
                const product = products.find((x) => x.id === id);
                const { title, image, price } = product;
                const amount = price * qty;

                return `
                    <div class="cart-item" data-id="${id}">
                        <img src="${image}" alt="${title}">
                        <div class="cart-item-details">
                            <h3>${title}</h3>
                            <h5>$${price}</h5>
                            <div class="cart-item-amount">
                                <i class="bi bi-dash-lg"></i>
                                <span class="qty">${qty}</span>
                                <i class="bi bi-plus-lg"></i>
                                <span class="cart-item-price">${amount}</span>
                            </div>
                        </div>
                    </div>
                `;
            }).join("");
            console.log('Cart rendered successfully.');
        }
    };

    //* API functions
    const loadProducts = async (apiURL) => {
        try {
            const response = await fetch(apiURL);
            if (!response.ok) {
                throw new Error(`HTTP error! Status=${response.status}`);
            }
            products = await response.json();
            console.log(products);
        } catch (error) {
            console.error(error);
        }
    };

    //* Initialize
    setupListeners();
    initStore();
});
1 Like

hello and welcome to fcc forum :slight_smile:

  • if you run this code without this callback function, it seems to be running fine
  • is that a jQuery kind of a thing?!

happy coding :slight_smile:

1 Like

There is nothing wrong with the code you posted but there is no connection between the state used on the two different pages. Each page has its own version of the code with a separate state.

You can use localStorage to share the state between pages (save the products and cart to localStorage and get the data on page load).


I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').


@bappyasif It is just a browser web API. Maybe you copied it without fixing the quotes (when the code posted isn’t properly formatted using backticks the forum will replace the quotes)