I am trying to implement simple increment and decrement functions within the following component:
(Note the bits that have been commented out)
I do not understand why I cannot place a hook inside of a handler function that then gets eventually fired by the user if the dependency array is populated by the part of the state subject to a change by the function itself.
Any help would be appreciated.
import React, { useState, useEffect } from 'react';
// helper function
function titleCase(string) {
return string[0].toUpperCase() + string.slice(1).toLowerCase();
}
function increment(value) {
return value + 1;
}
function decrement(value) {
return value - 1;
}
const Card = (props) => {
// const [cart_id, setCart_id] = useState(0);
const [toggleQuantity, setToggleQuantity] = useState(0);
let product_id = props.product_id;
let quantity = props.quantity;
let name = props.name;
let price = props.price;
let customer_id = props.customer_id;
/* useEffect(() => {
setToggleQuantity(quantity)
console.log(quantity)
}, [toggleQuantity]);
function useHandleIncrement(quantity) {
useEffect(() => {
setToggleQuantity(quantity + 1)
console.log(quantity)
}, [toggleQuantity]);
}
function useHandleDecrement(quantity) {
useEffect(() => {
setToggleQuantity(quantity - 1)
console.log(quantity)
}, [toggleQuantity]);
} */
function handleRemove() {
removeFromCart(props.cart_id)
};
/// Removing an item from the cart, does not work
// console.log(cart_id);
async function removeFromCart(cart_id) {
const url = `http:localhost:5000/carts/${cart_id}`
await fetch(url, {
method: 'DELETE',
success: function () {
alert('Item removed successfully')
},
error: function () {
alert('Error removing item')
}
});
}
async function handleCheckout() {
console.log('checking cart_id', props.cart_id);
await checkout(props.cart_id)
}
async function checkout(cart_id) {
const object = {
customer_id: customer_id,
price: price,
product_id: product_id,
quantity: quantity
}
try {
const response = await fetch(`http://localhost:5000/carts/${cart_id}/checkout`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'accept': 'application/json'
},
body: JSON.stringify(object)
})
return response.json();
} catch (error) {
console.error(error.message);
}
};
return (
<>
<p>{titleCase(name)}</p>
<p>Quantity:</p>
<p><button onClick={useHandleIncrement}>+</button>{quantity}<button onClick={useHandleDecrement}>-</button></p>
<h6>Price</h6>
<p>£ {quantity * price}</p>
<button onClick={handleRemove}>Remove from your cart</button>
<br />
<p>Complete payment:</p>
<button type="submit" name="payment" onClick={handleCheckout} >Pay Now</button>
<br />
</>
);
};
export default Card;