I’m doing a project using Vite and JS. I have a homepage component where I have code to add a product to the cart. This code works, but in 10% of cases, in the Chrome console, my product is undefined and not added to the cart. What could be the problem? Thanks!
export class HomePage extends Component {
constructor() {
super();
this.template = template();
this.state = {
orderCart: [],
};
}
addToCard = (e) => {
if (e.target.closest(".add-to-cart")) {
let price = e.target.parentElement.parentElement.dataset.price;
let name = e.target.parentElement.parentElement.parentElement.dataset.name;
let img = e.target.parentElement.parentElement.parentElement.dataset.img;
const cartItems = { price, name, img };
apiService.post("/order", cartItems).then(() => {
this.setState({
...this.state,
orderCart: this.state.orderCart?.concat(cartItems),
});
console.log(cartItems);
})
}
};
componentDidMount() {
this.addEventListener("click", this.addToCard);
}
componentWillUnmount() {
this.removeEventListener("click", this.addToCard);
}
}
customElements.define('home-page', HomePage);
For network query i use Axios Api.
For data storage I use Firebase(Realtime Database and Storage).
Product(I’m using Handlebars for HTML):
{{#each products}}
<div class="w-full md:w-1/3 xl:w-1/4 p-6 flex flex-col" data-id="{{this.id}}">
<div
data-img="{{this.img}}"
data-name="{{this.name}}"
>
<img class="hover:grow hover:shadow-lg" src="{{this.img}}" alt="product" />
<p data-name="{{this.name}}">{{this.name}}</p>
<div data-price="{{this.price}}" class="pt-3 flex items-center justify-between">
<p data-price="{{this.price}}" class="pt-1 text-gray-900">{{this.price}}</p>
<button class="add-to-cart">
<svg class="h-6 w-6 fill-current text-gray-500 hover:text-black" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12,4.595c-1.104-1.006-2.512-1.558-3.996-1.558c-1.578,0-3.072,0.623-4.213,1.758c-2.353,2.363-2.352,6.059,0.002,8.412 l7.332,7.332c0.17,0.299,0.498,0.492,0.875,0.492c0.322,0,0.609-0.163,0.792-0.409l7.415-7.415 c2.354-2.354,2.354-6.049-0.002-8.416c-1.137-1.131-2.631-1.754-4.209-1.754C14.513,3.037,13.104,3.589,12,4.595z M18.791,6.205 c1.563,1.571,1.564,4.025,0.002,5.588L12,18.586l-6.793-6.793C3.645,10.23,3.646,7.776,5.205,6.209 c0.76-0.756,1.754-1.172,2.799-1.172s2.035,0.416,2.789,1.17l0.5,0.5c0.391,0.391,1.023,0.391,1.414,0l0.5-0.5 C14.719,4.698,17.281,4.702,18.791,6.205z" />
</svg>
</button>
</div>
</div>
</div>
{{/each}}
I thought the problem might be with the add to cart button. I tried it by id, but the product was still undefined after several attempts.
