Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typeScript void error when sestate used in click handle

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading