Am new to TypeScript, am trying check if item already exist, but when am defining the previous variable am getting an error: Argument of type '(prev: CartItemsType[]) => CartItemsType[] | undefined' is not assignable to parameter of type 'SetStateAction<CartItemsType[]>', what am i doing wrong here
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}]
})
}
CodePudding user response:
You are calling setCartItems
with a function.
The problem is that your function doesn't always return a CartItemsType[]
it might return undefined.
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)
}
// your code has no return in this part.
return [...prev, {...clickedItem, amount:1}] // <<<<< missing return?
})
}