I am working on a cart storage mechanism where I have a handleAddClicked
function on a button. This function calls another addProductToCart
function passed in a Context API instance.
addProductToCart
takes in an object with an item, quantity, selectionIndices (main root of issue) and listIndex. selectionIndices
is set through a state variable in the view.
I’m expecting the product to be passed to the addProductToCart
function with the selectionIndices
value at the time. But as soon as I add another object, all of the cart items change to the current selectionIndices
value.
I believe this issue is stemming from the fact that I am passing the object with a reference to this.state.selectionIndices
instead of a constant variable. In other words, maybe I am looking for a way to pass state byVal not byRef.
I know that the issue is not in the main addProductToCart
function as hard-setting selectionIndices
passed fixes this issue completely. Also, I’ve tried setting state into a temp variable and passing that but it doesn’t work either.
state = {
product: {} as ProductType,
selectionIndices: [] as number[]
}
handleAddClicked = () => {
const ctx = this.context as CartContextType;
const product = {product: this.state.product, quantity: 1, selectionIndices: this.state.selectionIndices, listIndex: ctx.cartItems.length};
ctx.addProductToCart(product)
}
This bug has been driving me nuts! Any help would be greatly appreciated.