Search code examples
reactjsjson-server

How can i make it so that data sends only one item in array to cart


I'm trying to add the particular item in cart (which is located at react-db.json file) on button click, and later display it on a different page. Also if anyone has a simpler way of doing this it would be really helpfull

import React, { Component } from "react";
import Product from "./Product.jsx";
import { Kosarica } from "./kosarica.jsx";
import axios from "axios";

export default class Cart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: []
    };
  }
render() {
    return (
      <div>
        <div className="row">
          {this.state.products.map(prod => {
            return (
              <Product
                key={prod.id}
                product={prod}
                onIncrement={this.handleIncrement}
                onDecrement={this.handleDecrement}
                onDelete={this.handleDelete}
              >
                <button
                  id="btn"
                  className="btn btn-primary"
                  onClick={this.handleClick}
                >
                  Dodaj
                </button>
              </Product>
            );
          })}
        </div>
      </div>
    );
  }
componentDidMount = async () => {
    var response = await fetch("http://localhost:5000/products", {
      method: "GET"
    });

    var prods = await response.json();

    this.setState({ products: prods });
  };

};
  handleClick = product => {
    let data = [this.state.products];

    fetch("http://localhost:5000/cart", {
      method: "POST",
      mode: "cors",
      body: JSON.stringify(data)
    });
    console.log("data sent", data);
  };
}

note - increment, decrement and delete are working fine that's why i didn't post them here


Solution

  • <button
     id="btn"
     className="btn btn-primary"
     onClick={() => this.handleClick(prod)}
    >
    

    Then add cartItems into state, and in click handler :

    handleClick = (prod) => {
       this.setState({
         cartItems: [
          ...this.state.cartItems,
          prod
         ],
       });
    .... // then use cartItems to pass it to api end-point
    }