I am trying to store products in local storage but when a new product is added the previous one disappears. even though I am passing an array in local storage. when I click the same product again, it updates the array, but when a new product is added previous one is disappeared.
here the code of cardInsideView:
export default function CardInsideView() {
const [CartItems, setCartItems] = useState([])
const location = useLocation()
const AddItemsIntoCart =()=>{
console.log("working")
setCartItems([...CartItems,location.state])
}
useEffect(()=>{
if(CartItems.length){
localStorage.setItem("items",JSON.stringify(CartItems))
}
},[CartItems])
i have 3 screens , home Screen on which Cards are displayed, card inside view screen which gets data from uselocation, and Cart Screen which shows product stored in local storage.
here is the code of CartScreen
const getDataFromLocalStorage =()=>{
const data = localStorage.getItem("items")
if(data){
return JSON.parse(data)
}else{
return []
}
}
let data = getDataFromLocalStorage()
remember the local storage array updates when clicking on same product but not when we add new product. when same product is clicked
Try this instead
setCartItems([...localStorage.getItem("items"),location.state])