passing callback function to build cart functionality in React

Viewed 74

I'm trying to build an ecommerce Website, trying to build add to cart functionality, when i pass a callback function using props from a component to Parent component, it doesnt seem to work. I cant find any good documentation on this. I'm using commercejs as backend Here is my product code:

import React, { Component } from 'react';
import stripHtml from 'string-strip-html';
import { Card, ListGroup, ListGroupItem, Button} from 'react-bootstrap';

class ProductItem extends Component {
    constructor(props){
        super(props);
        this.handleAddToCart = this.handleAddToCart.bind(this);
    }
    handleAddToCart() {
        this.props.onAddToCart(this.props.product.id, 1);
    }
    render() {
        const { product } = this.props
        const { result } =(product.description);

        return(
            <Card style={{ width: '18rem' }}>
                <Card.Img variant="top" src={product.media.source} alt={product.name}  />
                <Card.Body>
                    <Card.Title>{product.name}</Card.Title>
                    <Card.Text>
                    {result}
                    </Card.Text>
                </Card.Body>
                <ListGroup className="list-group-flush">
                    <ListGroupItem>{product.price.formatted_with_symbol}</ListGroupItem>
                    <ListGroupItem>Dapibus ac facilisis in</ListGroupItem>
                </ListGroup>
                <Card.Body>
                    <Button name='Add to cart' className='product__btn' onClick={this.handleAddToCart}>Add to Cart</Button>
                    <Card.Link href="#">Another Link</Card.Link>
                </Card.Body>
                </Card>
        )
    }
}
export default ProductItem;

App.js file:

import React, { Component } from 'react';
import { commerce } from './lib/commerce';
import ProductsList from './components/ProductList';
import { Nav, Navbar, Form, FormControl, Button, NavDropdown} from 'react-bootstrap';
class App extends Component {
  constructor(props) {
    super(props);
    this.state={
      products:[],
      cart:{},
    }
  }
  componentDidMount() {
    this.fetchProducts();
    this.fetchCart();
  }
  fetchProducts() {
    commerce.products.list().then((products) => {
      this.setState({products: products.data});
    }).catch((error) => {
      console.log('There was an error fetching the products', error);
    });
  }
  fetchCart() {
    commerce.cart.retrieve().then((cart) => {
      this.setState({ cart });
    }).catch((error) => {
      console.error('There was an error fetching the cart', error);
    });
  }
  handleAddToCart(productId, quantity) {
    commerce.cart.add(productId, quantity).then((item) => {
      this.setState({cart: item.cart})
    }).catch((error) => {
      console.error('There was an error adding the item to the cart', error);
    });
  }
  render() {
    const { products } = this.state;
    return(
      <div className='App'>
        <Navbar bg="light" expand="lg">
        <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">
          <Nav className="mr-auto">
            <Nav.Link href="#home">Home</Nav.Link>
            <Nav.Link href="#link">Link</Nav.Link>
            <NavDropdown title="Dropdown" id="basic-nav-dropdown">
              <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
              <NavDropdown.Item href="#action/3.2">Another action</NavDropdown.Item>
              <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
              <NavDropdown.Divider />
              <NavDropdown.Item href="#action/3.4">Separated link</NavDropdown.Item>
            </NavDropdown>
          </Nav>
          <Form inline>
            <FormControl type="text" placeholder="Search" className="mr-sm-2" />
            <Button variant="outline-success">Search</Button>
          </Form>
        </Navbar.Collapse>
      </Navbar>
        <ProductsList products={products} onAddToCart={this.handleAddToCart}/>
      </div>
    )
  }
}

export default App;
1 Answers

You haven't actually called the function in the product list component right? Any reason for the same? You need to call the function even in the child component, just sending it won't help.

EDIT: You haven't bound the function in the parent component. Replace handleAddToCart(params) with handleAddToCart=(params)=> and the code should work

Related