I made a page that contains products and they should add to the cart. But after connecting the backend from asp.net core to the products page, add to cart button is not working on the Product.js page.
JavaScript
x
12
12
1
TypeError: addCart is not a function
2
onClick
3
src/Component/section/Products.js:56
4
53 | </h3>
5
54 | <span>LKR {product.price}</span>
6
55 | <p>{product.description}</p>
7
> 56 | <button onClick={()=> addCart(product.itemID)}>Add to cart</button>
8
| ^ 57 | </div>
9
58 | </div>
10
59 | ))
11
View compiled
12
context.js
JavaScript
1
103
103
1
import React, { Component } from 'react'
2
3
export const DataContext = React.createContext();
4
5
export class DataProvider extends Component {
6
state = {
7
products: [
8
9
10
],
11
cart: [],
12
total: 0
13
14
};
15
16
addCart = (id) =>{
17
const {products, cart} = this.state;
18
const check = cart.every(item =>{
19
return item.itemID !== id
20
})
21
if(check){
22
const data = products.filter(product =>{
23
return product.itemID === id
24
})
25
this.setState({cart: [cart,data]})
26
}else{
27
alert("The product is already in the cart ")
28
}
29
};
30
31
reduction = id =>{
32
const { cart } = this.state;
33
cart.forEach(item =>{
34
if(item.itemID === id){
35
item.count === 1 ? item.count = 1 : item.count -=1;
36
}
37
})
38
this.setState({cart: cart});
39
this.getTotal();
40
};
41
42
increase = id =>{
43
const { cart } = this.state;
44
cart.forEach(item =>{
45
if(item.itemID === id){
46
item.count += 1;
47
}
48
})
49
this.setState({cart: cart});
50
this.getTotal();
51
};
52
53
removeProduct = id =>{
54
if(window.confirm("Do you want to delete this product?")){
55
const {cart} = this.state;
56
cart.forEach((item, index) =>{
57
if(item.itemID === id){
58
cart.splice(index, 1)
59
}
60
})
61
this.setState({cart: cart});
62
this.getTotal();
63
}
64
65
};
66
67
getTotal = ()=>{
68
const{cart} = this.state;
69
const res = cart.reduce((prev, item) => {
70
return prev + (item.price * item.count);
71
},0)
72
this.setState({total: res})
73
};
74
75
componentDidUpdate(){
76
localStorage.setItem('dataCart', JSON.stringify(this.state.cart))
77
localStorage.setItem('dataTotal', JSON.stringify(this.state.total))
78
};
79
80
componentDidMount(){
81
const dataCart = JSON.parse(localStorage.getItem('dataCart'));
82
if(dataCart !== null){
83
this.setState({cart: dataCart});
84
}
85
const dataTotal = JSON.parse(localStorage.getItem('dataTotal'));
86
if(dataTotal !== null){
87
this.setState({total: dataTotal});
88
}
89
}
90
91
92
render() {
93
const {products, cart,total} = this.state;
94
const {addCart,reduction,increase,removeProduct,getTotal} = this;
95
return (
96
<DataContext.Provider
97
value={{products, addCart, cart, reduction,increase,removeProduct,total,getTotal}}>
98
{this.props.children}
99
</DataContext.Provider>
100
)
101
}
102
}
103
Products.js
JavaScript
1
67
67
1
import React, { Component } from 'react'
2
import {Link} from 'react-router-dom'
3
import {DataContext} from '../Context'
4
import '../css/Products.css'
5
import axios from 'axios';
6
7
8
export class Products extends Component {
9
10
static contextType = DataContext;
11
12
13
constructor(props) {
14
super(props);
15
this.state = { products: [] }
16
}
17
async componentDidMount() {
18
try {
19
const res = await axios.get('https://localhost:5001/api/Items');
20
console.log("he, he", res.data);
21
this.setState({ products: res.data });
22
//this.state.products = res.data;
23
console.log("uu", this.state.products);
24
} catch (error) {
25
console.log('er er', error)
26
}
27
28
29
30
31
}
32
33
render() {
34
const {products, addCart} = this.state;
35
//const { products} = this.state;
36
// const {addcart} =this;
37
38
39
return (
40
41
<div id="product">
42
43
{
44
45
products.map(product =>(
46
<div className="card" key={product.itemID}>
47
<Link to={`/product/${product.itemID}`}>
48
<img src={`https://localhost:5001/${product.src}`} alt=""/>
49
</Link>
50
<div className="content">
51
<h3>
52
<Link to={`/product/${product.itemID}`}>{product.title}</Link>
53
</h3>
54
<span>LKR {product.price}</span>
55
<p>{product.description}</p>
56
<button onClick={()=> addCart(product.itemID)}>Add to cart</button>
57
</div>
58
</div>
59
))
60
}
61
</div>
62
)
63
}
64
}
65
66
export default Products;
67
Also there is a problem in this details.js page backend data is showing on console.But it does not displaying as a user interface in frontend.
Details.js
JavaScript
1
90
90
1
import React, { Component } from 'react'
2
import {DataContext} from '../Context'
3
import {Link} from 'react-router-dom'
4
import Colors from './Colors'
5
import '../css/Details.css'
6
import axios from 'axios';
7
8
9
10
export class Details extends Component {
11
static contextType = DataContext;
12
13
constructor(props) {
14
super(props);
15
this.state = { products: [] }
16
}
17
18
async componentDidMount() {
19
this.getProduct();
20
try {
21
var id =this.props.match.params.id;
22
const res = await axios.get(`https://localhost:5001/api/Items/${id}`);
23
console.log("he, he", res.data);
24
this.setState({ products: res.data });
25
this.state.products.id = res.data;
26
console.log("uu", this.state.products.itemID);
27
} catch (error) {
28
console.log('er er', error)
29
}
30
31
32
33
34
}
35
36
37
getProduct = () =>{
38
if(this.props.match.params.id){
39
const res = this.state.products;
40
const data = res.filter(item =>{
41
return item.id === this.props.match.params.id
42
})
43
this.setState({products: res.data});
44
this.state.products.id = res.data;
45
}
46
};
47
48
// componentDidMount(){
49
// this.getProduct();
50
// }
51
52
53
// constructor(props) {
54
// super(props);
55
// this.state = { products: [] }
56
// }
57
58
render() {
59
const {product} = this.state;
60
// const {addCart} = this.context;
61
return (
62
<>
63
{
64
product && product.length!=0 ? product.map(item =>(
65
<div className="details" key={item.itemID}>
66
<Link to={`/item/${item.itemID}`}>
67
<img src={`https://localhost:5001/${item.src}`} alt=""/>
68
</Link>
69
<div className="box">
70
<div className="row">
71
<h2> <Link to={`/item/${item.itemID}`}>{item.title}</Link></h2>
72
<span>LKR {item.price}</span>
73
</div>
74
{/* <Colors colors={item.colors}/> */}
75
<p>{item.description}</p>
76
<p>{item.content}</p>
77
{/* <Link to="/cart" className="dcart" onClick={() => addCart(item.itemID)}>
78
Add to cart
79
</Link> */}
80
</div>
81
</div>
82
))
83
:''}
84
</>
85
)
86
}
87
}
88
89
export default Details
90
Cart.js
JavaScript
1
144
144
1
import React, { Component } from 'react'
2
import {DataContext} from '../Context'
3
import {Link} from 'react-router-dom'
4
import Colors from './Colors'
5
import '../css/Details.css'
6
import '../css/Cart.css'
7
import { Button } from '../Button/Button'
8
import StripeCheckout from 'react-stripe-checkout'
9
import axios from 'axios';
10
import {toast} from 'react-toastify';
11
import GooglePayButton from '@google-pay/button-react';
12
13
14
export class Cart extends Component {
15
16
17
static contextType = DataContext;
18
19
20
componentDidMount(){
21
this.context.getTotal();
22
toast.configure();
23
}
24
25
render() {
26
const {cart,increase,reduction,removeProduct,total} = this.context;
27
28
29
async function handleToken(token, addresses){
30
//console.log({token, addresses})
31
const response = await axios.post('https://iemcj.sse.codesandbox.io/checkout', {
32
token,
33
//item
34
});
35
const {status} =response.data
36
if (status === 'success'){
37
toast('Success! Check emails for details',
38
{type: 'success'})
39
} else{
40
toast('Something went wrong',
41
{type: 'error'})
42
43
}
44
45
}
46
if(cart.length === 0){
47
return <h2 style={{textAlign:"center"}}>Your Cart is Empty</h2>
48
}else{
49
return (
50
<>
51
{
52
cart.map(item =>(
53
<div className="details cart" key={`https://localhost:5001/${item.itemID}`}>
54
<img src={`https://localhost:5001/${item.src}`} width="400" alt=""/>
55
<div className="box">
56
<div className="row">
57
<h2>{item.title}</h2>
58
<span>LKR {item.price * item.count}</span>
59
</div>
60
<Colors colors={item.colors}/>
61
<h4>{item.description}</h4>
62
<p>{item.content}</p>
63
<div className="amount">
64
<button className="count" onClick={() => reduction(item.itemID)}> - </button>
65
<span>{item.count}</span>
66
<button className="count" onClick={() => increase(item.itemID)}> + </button>
67
</div>
68
</div>
69
<div className="delete" onClick={() => removeProduct(item.itemID)}>X</div>
70
71
</div>
72
73
))
74
}
75
76
77
<div className="total">
78
{/* <Link to="/checkout">Payment</Link> */}
79
80
81
<GooglePayButton
82
environment="TEST"
83
paymentRequest={{
84
apiVersion:2,
85
apiVersionMinor:0,
86
allowedPaymentMethods: [
87
{
88
type: 'CARD',
89
parameters:{
90
allowedAuthMethods: ['CRYPTOGRAM_3DS', 'PAN_ONLY'],
91
allowedCardNetworks: ['MASTERCARD', 'VISA'],
92
},
93
tokenizationSpecification:{
94
type: 'PAYMENT_GATEWAY',
95
parameters: {
96
gateway: 'example',
97
gatewayMerchantID: 'exampleGatewayMerchantID',
98
},
99
},
100
},
101
],
102
merchantInfo: {
103
merchantId: '12345678901234567890',
104
merchantName:'Example Merchant',
105
},
106
transactionInfo:{
107
totalPriceStatus:'FINAL',
108
totalPriceLabel: 'Total',
109
totalPrice:`${total}`,
110
currencyCode:'LKR',
111
countryCode:'LK',
112
},
113
shippingAddressRequired:true,
114
callbackIntents:['SHIPPING_ADDRESS','PAYMENT_AUTHORIZATION'],
115
}}
116
onLoadPaymentData={paymentRequest => {
117
console.log('Success', paymentRequest);
118
}}
119
onPaymentAuthorized={paymentData => {
120
console.log('Payment Authorised Success', paymentData)
121
return { transactionState: 'SUCCESS'}
122
}}
123
onPaymentDataChanged={paymentData => {
124
console.log('On Payment Data Changed', paymentData)
125
return { }
126
}}
127
existingPaymentMethodRequired='false'
128
buttonColor='black'
129
buttonType='buy'
130
131
132
/>
133
134
135
<h3>Total: LKR {total}</h3>
136
</div>
137
</>
138
)
139
}
140
}
141
}
142
143
export default Cart
144
Section.js
JavaScript
1
31
31
1
import React, { Component } from 'react'
2
import Products from './section/Products'
3
import Details from './section/Details'
4
import {Route} from "react-router-dom"
5
import Cart from './section/Cart'
6
import Payment from './section/Payment'
7
import Confirmation from './Payment/Confirmation'
8
import {Link} from 'react-router-dom'
9
10
import '../Component/Section.css'
11
12
13
class Section extends React.Component{
14
render(){
15
return(
16
<div className="section">
17
<section>
18
<Route path="/product" component={Products} exact />
19
<Route path="/product/:itemID" component={Details} exact />
20
<Route path="/cart" component={Cart} exact/>
21
<Route path="/payment" component={Confirmation} exact />
22
23
</section>
24
</div>
25
)
26
27
}
28
}
29
30
export default Section
31
Advertisement
Answer
in Details.js this.setState({ products: res.data });
===> this.setState({ product: res.data });
.
and use condition:
JavaScript
1
2
1
{product && product.length!=0 ? product.map(product =>///your code) :'' }
2