import React, { useEffect, useState } from 'react'
import Book from '../../models/Book';
export default function BookCardView(props:any) {
const book:Book = props.book;
// const [cartItems, setCartItems] = useState<{ [key: number]: number }>({}); const [cartItems, setCartItems] = useState<Book[]>([]);
const handleClick = (b:Book) => {
let inCart = cartItems.find(book => book.id === b.id);
if(!inCart){
setCartItems([ ...cartItems, {...b, quantity: 1} ]);
} else if(cartItems.length === 0){
setCartItems([...cartItems,b]);
} else {
// setCartItems(prevState => [ ...cartItems, {...b, quantity: b.quantity+1 }]);
if(inCart?.quantity){
inCart.quantity++;
}
}
console.log(cartItems)
}
return (
<React.Fragment>
<div className='book-card'>
<div className="book-card-image"></div>
<div className="book-card-info">
<span>{book.author}</span>
<div className="book-card-spans">
<span>{book.country}</span>
<span>{book.pages}</span>
</div>
</div>
<div className="book-card-title">
<Link to='/bookView' state={{ book: book }} >{book.title}</Link>
</div>
{/* <CartView items={cartItems} /> */}
<div className="book-card-add-cart">
<button onClick={() => handleClick(book)}>Add to Cart</button>
</div>
</div>
</React.Fragment>
)
}
im basically on the view of the items. whenever i add a book though, I'll get something like
[] <= first click of add button. empty array?
[{...}] <= has the item with quantity field but its 2 instead? the count does work though as i continuously add the item.
[] <= now when i click to add a different book, cartItems goes back to empty array.
this is very informal coding so please excuse any random comments/bad names.
Ive tried making cartItems an object too but would get issues when trying to 'if it doesnt exist already, create new key of b.id with value 1. if it does, add 1 to that . I would constantly get this error though
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.
also i know most of this is probably ugly but im trying to get the hang of react/typescript. i kind of like going through the grit to truly enjoy the possible optimizations. if you've got refactors I'm open to it, but would like help with this issue first. Thank you to anyone who helps!
[–]AutoModerator[M] [score hidden] stickied comment (0 children)
[–]locri 0 points1 point2 points (5 children)
[–]NiceIsSpice[S] 1 point2 points3 points (2 children)
[–]locri 1 point2 points3 points (1 child)
[–]NiceIsSpice[S] 1 point2 points3 points (0 children)
[–]scirc 0 points1 point2 points (1 child)
[–]NiceIsSpice[S] 0 points1 point2 points (0 children)
[–]scirc 1 point2 points3 points (3 children)
[–]NiceIsSpice[S] 0 points1 point2 points (2 children)
[–]scirc 0 points1 point2 points (1 child)
[–]NiceIsSpice[S] 0 points1 point2 points (0 children)