State is defined like so:
const [items, setItems] = useState([] as CartItemType[]);
const [id, setId] = useState<number | undefined>();
In this case, id
is totally useless. Don't need it in my app at all.
However, if I try to update items
, the state variable doesn't change and the UI doesn't reload, unless I also update id
:
useEffect(() => console.log("reload")); // only fires if I include setId
const clickItem = (item: CartItemType) => {
let tempItems = data;
// @ts-ignore
tempItems[item.id - 1].animation =
"item animate__animated animate__zoomOut";
setItems(tempItems!); // "!" to get rid of ts complaint about possible undefined value
setId(item.id); // nothing happens if I don't include this
};
// ... inside the return, in a map fn
<Item
item={item}
handleAddToCart={handleAddToCart}
clickItem={clickItem}
/>
// inside Item component
<StyledItemWrapper
className={item.animation}
onClick={() => {
clickItem(item); // item = an obj containing an id and an animation property
}}
>
Why is setId
necessary here? What is it doing that setItems
isn't?