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

There was an issue with the installation of "ethereumjs-abi" from the directory "node_modules/eth-sig-util/ethereumjs-abi@git+https:/github.com/ethereumjs/ethereumjs-

After accidentally deleting the .next and node_modules folder while experimenting, I attempted to run npm i, which resulted in the error message below: $ npm i npm ERR! code ENOLOCAL npm ERR! Could not install from "node_modules/eth-sig-util/ethereumj ...

Tips for inserting a pin into a designated location on an image map

Within my angular application, I have implemented an image map using the HTML usemap feature. Here is the code snippet: <img src="../../assets/floor2.jpg" usemap="#floor2Map"> <map name="floor2Map"> <area shape="pol ...

What is the purpose of specifying http://localhost:3000 when accessing API routes in Next.js?

I created an API route within the pages directory of my NextJS project. It is functioning properly as I am able to retrieve data by directly accessing the URL like http://localhost:3000/api/tv/popular. My goal is to fetch this data using getStaticProps and ...

Retrieve information stored in a JSON data field within the results of an npm

How can I properly access the value of DepDateTime from the first object? Here is my current attempt: const nodeSkanetrafiken = require('node-skanetrafiken'); const from = { name: 'Bjärred centrum', id: 62025, type: 0 }; const to = ...

Using Vue.js to send a slot to a child component in a nested structure

Check out this interesting modal component configuration //modal setup <template> <slot></slot> <slot name='buttons'></slot> </template> Imagine using it like a wizard //wizard setup <template> ...

Assigning properties to the constructor using `this.prop`

Within a React class component, I have multiple methods and the component receives various props. I am contemplating whether I should assign each prop as this.propName in the constructor and then access them using this.propName. For your reference, below ...

Contrast in executing an Arrow Function versus a regular Function when passing them as Props in REACTJS

Here is the component code: <SelectCampanha titulo="Preenchimento obrigatório" listaOpcoes={ category ? riskModel.filter((item) => item.CategoryType.includes(categoria) ...

Unable to access path for children through buttons in parent path

As a data scientist entering the world of frontend development, I find myself faced with the task of creating a UI at the request of my boss. Please bear with me as I attempt to explain my issue in layman's terms. Currently, I am using Vue.js and hav ...

What steps can I take to troubleshoot the cause of my browser freezing when I try to navigate to a different webpage

Within this div, users can click on the following code: <div id="generate2_pos" onclick="damperdesign_payload();" class="button">Generate P-Spectra</div> Upon clicking, the damperdesign_payload() function is triggered, leading to a link to an ...

Avoid running another process before the current one finishes in jQuery

I have a situation where I am using $.ajax inside a for loop in jQuery. for(var i=0; i < 2; i++) { $.ajax({ url :"/models/getdata"+i, dataType:"json", success:function(data) { } }); } The issue is that before the success function for i=0 completes, ...

Unlock the Power of Vue Draggable in Vue.js 3 with These Simple Steps

When attempting to implement Draggable in Vue.js 3, I encountered an error message: VueCompilerError: v-slot can only be used on components or <template> tags. Below is a snippet of my code: <draggable tag="transiton-group" name="s ...

Adjust the class based on the number of li elements

When there are more than two (li) tags, the ul tag should have the class "col_3"; otherwise it should have the class "col_2" For instance: If there are two columns <div class="container"> <ul class="col_2"> <li>One</li> ...

Error: Trying to destructure a non-iterable object with useContext in React is not valid

ERROR [TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.] Using UserContext : import React, { useContext, useEffect, useLayoutEffect, useState } from "reac ...

What causes an error when trying to pass an object containing a file path for an image and applying it to the bg-[url()] property in Tailwind CSS?

https://i.stack.imgur.com/XeaC0.png https://i.stack.imgur.com/MxL3K.png The picture is dynamically adjusting itself upon loading. Additionally, I am interested in learning an alternative method of using the next.js Image tag to set the background and add ...

CSS styling not rendering consistently across various web browsers

Hey everyone! I've encountered an issue with my webpage. Feel free to check out the code on my CodePen here. When I view this page on Safari, everything looks perfect. However, when I switch over to Chrome or Firefox, the layout is all messed up. Ele ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

Alignment of text fields in a vertical manner

How can I vertically align text input fields using CSS? <form action='<?= $_SERVER['PHP_SELF']; ?>' method='post'> <p><label for='username' class=''>Username:</label& ...

Tips on aligning an entire text in R Markdown using the bookdown::gitbook function as the desired output

I've been looking for a way to justify the text in my gitbook, but haven't had any luck finding a solution. I've attempted: Adding "text-align: justified" to the CSS right after the YAML Header: <style> body { text-align: justify ...

Refresh kid using timer

I am facing an issue with my save prompt feature, which appears when different parent components submit data to the server. The save prompt is a simple component that looks like this: export class PromptComponent extends React.Component<{}, {}> { co ...

Executing function after completion of ajax call

I have 2 buttons and 3 links that trigger an ajax request. I want to display an alert only when the request initiated by one of the buttons is completed, but not when a link is clicked. Below is my code: HTML: <button id="ajax1">Ajax 1</button&g ...