'TypeError: state.find is not a function
I try to use the find() method but I get
cartItems.find is not a function
what happens? and how to fix it?
import React, {useState} from 'react'
function cart() {
const [cartItems, setCartItems] = useState([])
const add = (pro) => {
const exist = cartItems.find((item) => {
return item.id === pro.id;
});
if (exist) {
setCartItems(
cartItems.find((item) => {
return item.id === exist.id
? {...exist, qnty: exist.qnty + 1}
: item;
})
);
} else {
setCartItems([...cartItems, {...pro, qnty: 1}]);
}
};
return (
<div>cart</div>
)
}
export default cart
Solution 1:[1]
This happen because cartItems is no longer an array.
According to here:
The find() method returns the first element in the provided array that satisfies the provided testing function.
In this part of your code -
setCartItems(
cartItems.find((item) => {
return item.id === exist.id
? {...exist, qnty: exist.qnty + 1}
: item;
})
);
You set cartItems to be the first element of your condition there with find(). So next render, cartItems is no longer an array, but a an item. Which have no find.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Omri Attiya |
