I am new to TypeScript and trying to check if an item already exists. However, when I define the previous variable, I'm encountering an error: "Argument of type '(prev: CartItemsType[]) => CartItemsType[] | undefined' is not assignable to parameter of type 'SetStateAction
Here’s my code:
export type CartItemsType ={
title: string
id: number
description: string
images: string
price: number
amount: number
}
const [cartItems, setCartItems] = useState<CartItemsType[]>([] as CartItemsType[])
const handleAddToCart = (clickedItem:CartItemsType) => {
setCartItems(prev => {
//check if item is already in cart
const isItemInCart = prev.find(item => item.id === clickedItem.id)
if(isItemInCart){
return prev.map( item => item.id === clickedItem.id? {...item, amount: item.amount + 1}: item)
}
[...prev, {...clickedItem, amount:1}]
})
}