Home > Mobile >  typeScript void error when sestate used in click handle
typeScript void error when sestate used in click handle

Time:06-07

when i want use sestate (setCardItem) throw this error :
Argument of type '(prev: cartItemType[]) => cartItemType[] | void[]' is not assignable to parameter of type 'SetStateAction<cartItemType[]>'. all of the code

type cartItemType = {
  id: number;
  title: string;
  price: number;
  description: string;
  category: string;
  image: string;
  amount: number;
};
    const [cardItem, setCardItem] = useState<cartItemType[] >([]);
    const handleClickAddToCard = (clickedItem: cartItemType) => {
        setCardItem(prev => {
          // 1. is the item already added in the card?
          const isItemInCard = prev.find((item) => item.id === clickedItem.id);
          if (isItemInCard) {
            return prev.map((item) => {
              item.id === clickedItem.id
              ? { ...item, amount: item.amount   1 }
              : item;
            });
          }
          // 2. first time item added in card
          return [...prev, { ...clickedItem, amount: 1 }];
        });
        
      };

this is all of the code and declared state cardItem

code error info when setCardItem (prev => {}) type script erorr says: void dos not assainable to prev type

CodePudding user response:

Look closely at your map invocation. There is no return statement, so by design it returns void. You probably wanted to use parentheses instead of braces. If you want to stay with braces use following code:

if (isItemInCard) {
    return prev.map((item) => {
        return item.id === clickedItem.id ?
            { ...item, amount: item.amount   1 } :
            item;
    });
}
  • Related