Im trying to keep the state of cart after add it Item to cart by using context and save it to localstorage. The add to cart function is work well and the cart also update item into it.
Check LocalStorage that it has been saved the item into it as well!
But when i reload page or switch page back to home page, all datas has been reset
This is my cart context:
import { createContext, useContext, useState, useEffect } from "react";
// import { Items } from "../../Data/AllDatas";
const CartContext = createContext();
export const CartProvider =({children})=>{
const [cartItem, setCartItem] = useState([])
const [qty, setQty] = useState(1);
const [showCart, setShowCart] = useState(false);
const [totalQty, setTotalQty] = useState(0);
const [totalPrice, setTotalPrice] = useState();
const increaseQty = ()=>{
setQty(prevQty => prevQty+1)
}
const decreaseQty = () =>{
setQty((prevQty)=>{
if(prevQty - 1< 1)return 1
return prevQty-1
})
}
useEffect(() => {
const json = localStorage.getItem('cartItem')
const savedCart = JSON.parse(json)
if(savedCart){
setCartItem(savedCart)
}
}, []);
useEffect(() => {
const json = JSON.stringify(cartItem);
localStorage.setItem("cartItem", json);
}, [cartItem]);
console.log(cartItem)
// {id: 1, quantity :1}
const addToCart = (Item, quantity)=>{
const checkProduct = cartItem.find((product)=> product.id === Item.id)
setTotalPrice((prevTotalPrice)=>prevTotalPrice + prevTotalPrice*quantity)
setTotalQty((prevTotalQty)=> prevTotalQty + quantity)
if(checkProduct){
const updateCart = cartItem.map((cartProduct)=>{
if(cartProduct.id === Item.id)return{
...cartProduct,
quantity: cartProduct.quantity + quantity
}
})
setCartItem(updateCart);
setQty(1);
}else{
Item.quantity = quantity;
setCartItem([...cartItem, {...Item}])
}
}
const contextValue = {
showCart,
qty,
totalPrice,
increaseQty,
decreaseQty,
totalQty,
addToCart,
setShowCart,
setCartItem,
cartItem
}
return(
<CartContext.Provider value ={contextValue}>
{children}
</CartContext.Provider>
)
}
export const useCartProvider = () => useContext(CartContext)
and here is app.js:
//import Cart from './Components/Cart';
import {Routes, Route} from 'react-router-dom';
import Header from './Components/Header/Header';
import HomePage from './Pages/HomePage/HomePage';
import New from './Pages/NewArrival/New';
import All from './Components/AllProducts/All';
import NewC from './Pages/NewCollection/NewC';
import Footer from './Components/Footer/Footer';
import Product from './Components/Products/Product';
import { CartProvider } from './Components/CartProvider/CartContext';
const App = ()=> {
return (
<CartProvider>
<Header/>
<Routes>
<Route path='/' element={<HomePage/>}/>
<Route>
<Route path="/newArrival" element={<New/>}/>
<Route path="/All" element={<All/>}/>
<Route path="/NewCollection" element={<NewC/>}/>
</Route>
<Route path="/product/:id" element={<Product/>}/>
</Routes>
<Footer/>
</CartProvider>
);
}
export default App;
here is product.js:
import React, {useState, useEffect } from 'react'
import {Items} from '../../Data/AllDatas';
import { useParams } from 'react-router';
import './Product.css';
import {useCartProvider} from '../CartProvider/CartContext';
const Product = () => {
const {id} = useParams();
const Item = Items.filter((Item) => Item.id === parseInt(id));
const [image, setImage] = useState(Item[0].front)
const {qty, decreaseQty, increaseQty, addToCart} = useCartProvider()
const changeImage= (e) =>{
setImage(e.target.src)
}
return (
<div className='containerProduct'>
<div className='route'>
<p>Home/ </p>
<p>Ready To Wear/ </p>
<p> {Item[0].des}</p>
</div>
<div>
<div className='productDisplay'>
<div className='left'>
<div className='smallImg'>
<img src={Item[0].front}
onClick={changeImage}/>
<img src={Item[0].back}
onClick={changeImage}/>
</div>
<div className='bigImg'>
<img src={image} alt={image}/>
</div>
</div>
<div className='right'>
<p>{Item[0].des}</p>
<h4>{Item[0].price}</h4>
<div className='addItem'>
<h1>Quantity: </h1>
<button onClick={decreaseQty}>-</button>
<h1>{qty}</h1>
<button onClick={increaseQty}>+</button>
</div>
<div className='button'>
<button
onClick={() => addToCart(Item[0], qty)}
>
Add to cart
</button>
<button>Buy now</button>
</div>
</div>
</div>
</div>
<div className='des'>
<p>Detail: {Item[0].detail}</p>
</div>
</div>
)
}
export default Product;
Im trying to keep the state of cart after add it Item to cart by using context and save it to localstorage. The add to cart function is work well and the cart also update item into it.
Check LocalStorage that it has been saved the item into it as well!
But when i reload page or switch page back to home page, all datas has been reset
2
Answers
there might be a small issue causing the data to reset after a reload or page switch.
Make sure that the key used to store and retrieve data in local storage is consistent
When you set the initial state of the cart items in the CartContext using useState([]), it might be overwritten by the local storage value if it exists. To avoid this,
Debug and log the local storage value to ensure that it contains the correct data.
Your useState is resetting the state to an empty array on page load because of ur useEffect logic. You need to check if an item already exists in the localstorage and set the array to it if it does. For eg.