I encountered an issue with my shopping cart while using ReactJS

this is the App.js file

import React from "react";
import ListProduct from "./listProduct";
import ListOrder from "./listOrder";
import pizza from "./pizza.jpg";
import './style.css'
import { Container,Row,Col,Button } from 'react-bootstrap';
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      total: 0,
      count: 0,
      products: [
        { id: 0, name: "Cold cuts", price: 5, value: 0, src: pizza },
        { id: 1, name: "Pepperoni", price: 3.5, value: 0, src: pizza },
        { id: 2, name: "Feta", price: 2.5, value: 0, src: pizza },
        { id: 3, name: "Mozzarella", price: 1.5, value: 0, src: pizza },
        { id: 4, name: "Swiss cheese", price: 1.5, value: 0, src: pizza },
        { id: 5, name: "Spices", price: 0.5, value: 0, src: pizza },
        { id: 6, name: "Vegetables", price: 0.5, value: 0, src: pizza },
      ],
      foodsOrder: [],
    };
  }
  handleIncrement = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };
  render() {
    return (
      <Container >
        <Row>
          <Col xs = {8}>
              <ListOrder />
          </Col>
          <Col className = 'item'>
            <Row className = 'header'>
              <span>Your pizza : </span>
              <span>$</span>
              <Button variant = 'warning'>Reset Pizza</Button>
            </Row>
            <ListProduct
              count={this.state.count}
              handleIncrement={this.handleIncrement}
              products = {this.state.products}
            />
          </Col>  
        </Row>
      </Container>
    );
  }
}
export default App;

this is the listProduct.js file

import React, { Component } from "react";
import Item from "./Item";
import {Row,Button} from 'react-bootstrap';
class ListProduct extends React.Component {
    render() {
    const {handleIncrement,count,products} = this.props
    return (
      <>

       {products.map(product =>  <Item key = {`${product.id}`} {...product}
          handleIncrement={handleIncrement}
          count={count}
        />)
       }
      </>
    );
  }
}

export default ListProduct;

this is the Item.js file

import React from 'react'
import ListProduct from './listProduct';
import {Row,Col,Button,Badge } from 'react-bootstrap';
class Item extends React.Component{
    render(){
            const {id,name,price,value,pizza} = this.props
            const {handleIncrement,count} = this.props
        return (
        <>
        <Row className = 'item'>
            <Col className = 'information'>
                <p>{name}</p>
                <p>{`${price} $`}</p>   
            </Col>
            <Col className = 'button'>
                <Button className = 'add' variant = 'success' onClick = {() => {handleIncrement(id)}} >+</Button>
                <Badge>{count}</Badge>
                <Button className = 'delete' variant="danger">-</Button>
            </Col>
        </Row>
        </>
        )
    }
}
export default Item;

When I click the event handler in the button, all variables in `this.state.count` in the `App` class increase as shown in the following image. I've tried other ways but it hasn't worked: https://i.stack.imgur.com/owUPZ.png

I want that when I click a button, only that specific button gets executed. Help me with this issue. Thank you so much........................................

Answer №1

When it comes to managing the count of products, you have been storing just one solitary count. The issue lies in how the state is saved within the App component, thus resulting in a single count for all products listed. To overcome this limitation, you can opt to either preserve a list of counts within the App component and update them accordingly, or assign individual states to each item on the list to keep track of their distinct counts.

Answer №2

Using count as the total may not be what you intended.

If you want to keep track of each product individually, consider separating the count for each product.

constructor() {
    super();
    this.state = {
      total: 0,
      products: [
        { id: 0, count: 0, name: "Cold cuts", price: 5, value: 0, src: pizza },
        { id: 1, count: 0, name: "Pepperoni", price: 3.5, value: 0, src: pizza },
        { id: 2, count: 0, name: "Feta", price: 2.5, value: 0, src: pizza },
        { id: 3, count: 0, name: "Mozzarella", price: 1.5, value: 0, src: pizza },
        { id: 4, count: 0, name: "Swiss cheese", price: 1.5, value: 0, src: pizza },
        { id: 5, count: 0, name: "Spices", price: 0.5, value: 0, src: pizza },
        { id: 6, count: 0, name: "Vegetable", price: 0.5, value: 0, src: pizza },
      ],
      foodsOrder: [],
    };
  }

Additionally, consider updating your Increase function accordingly.

handleIncrement = (id) => {
  this.setState({
    products: this.state.products.map((item) => item.id === id ? {...item, count:item.count+1} : {...item});
  });
}

Instead of using count, consider utilizing the value attribute for a more organized approach.

Answer №3

It appears that the state.count is being used uniformly across all products. Have you considered incorporating count into each individual product object within state.products? This adjustment would likely necessitate a modification in how the products are passed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is a method to position an <img> on top of text without obscuring the text or resorting to CSS background or text-indent

To view the related code snippet, click on this link: http://jsfiddle.net/Ws8ux/ Is there a way to position the text under the logo without hiding it through display:none or text-indent? I am aiming to bring the image up while keeping the logo in the back ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

What is the best way to execute JavaScript on the main MVC page when an AJAX request in a partial view has finished?

My Asp.net MVC partial view is designed for searching and makes an Ajax call to retrieve results. After the results are displayed, the user can select a search result by clicking on a link in one of the rows. Upon selecting a search result, an Ajax post re ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for this in Chart.js? Thanks! ...

Combining two numbers retrieved from Firebase using React

Hello, I am new to React and finding it challenging to perform mathematical calculations with React. I have been attempting to add two values retrieved from a Firebase database, but they keep displaying as strings without adding the actual values together. ...

Issue with array doesn't update when switching positions of elements

I encountered a strange issue while working on my visualizer for sorting algorithms. Everything was going smoothly until I reached the Selection Sort algorithm. The problem lies in the fact that the i value doesn't seem to change during each pass, cau ...

What is the process for converting/executing TypeScript into JavaScript?

Having trouble running https://github.com/airgram/airgram Encountering this warning message from the post (node:9374) Warning: To load an ES module, set "type": "module" Have already added {"type": "module"} To pa ...

centering headers using tailwind styles

I am facing a challenge with positioning my main title, logo, and subtitle. I want the subtitle to be centered regardless of the logo's width. Currently, the position of the sub title changes based on the logo's width, resulting in it not aligni ...

Troubleshooting Problems with Cascading Style Sheets

Struggling with a layout issue on my website. I need to display an image with text at the beginning of the site-wrap div under the name background-image, with the text inside that div. Adding line-height to the text div adjusts its height, but I want to m ...

What steps can be taken to resolve the issue of Ajax not retrieving any data from

I'm struggling to identify the error in this code. I have created a search bar and implemented AJAX to automatically fetch data. Here is the HTML file: <!DOCTYPE html> <html> <head> <title></title> <script ...

What could be the reason for my image not loading properly in Vue.js 3?

I'm struggling to load an image using a relative path and value binding with v-for in my template code. Despite following the correct syntax, the website is displaying an error indicating that it can't retrieve the image. Here's a snippet of ...

Tips on entering a text field that automatically fills in using Python Selenium

One of the challenges I am facing on my website is an address input text field that gets automatically populated using javascript. Unlike a drop-down field where you can select values or a standard text field where you can manually type in information, thi ...

What is the best way to supply JSON data to the "The Wall" MooTools plugin while feeding?

I came across this amazing plugin called "The Wall" but unfortunately, neither the documentation nor the examples demonstrate how to utilize JSON objects with it. Imagine we have a JSON array like: [ { href : "/my/photo/image1.jpg", title : "Me an ...

Encountering a "ref missing" error when attempting to integrate Draft.js with Material

I am currently facing challenges when trying to integrate Draft.js with Material UI's TextField component (or Input). Even after following the provided documentation (https://material-ui.com/components/text-fields/#integration-with-3rd-party-input-lib ...

How to create fading directional navigation arrows using the Orbit jQuery plugin?

I want the navigation arrows to only appear when the user hovers over the "#featured" div or its display. My current code achieves this, but the transition is quite abrupt: $("#featured, div.slider-nav").hover(function(){ $("div.slider-nav").animate({ ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Tips for spinning a div with jQuery as it animatesRotate a div and animate it simultaneously using

Currently, I have a piece of code that enables my div element to move and change its size. $(document).ready(function(){ $("#box").animate({ top: "250px", left: "500px", width: '300px', height: '250px& ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

The post method is functioning properly in browsers such as Firefox, Internet Explorer, and Chrome; however, it is not working in the Edge browser

I am encountering an issue with a post method in the Edge browser. Even though I am able to receive responses for the same request in other browsers like Internet Explorer, Chrome, and Firefox, Edge seems to be not responding at all. Despite conducting a s ...