NextJS如何正确保存会话与产品添加到购物车

r9f1avp5  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(69)

我正在寻找一个解决方案,如何正确地持有产品添加到购物车中的会话.目前我解决了这种方式:
page.tsx

const ProductPage = () => {
  const { product, loading, error } = useProductData();
  const { cart, addToCart: addToCartHook } = useCartItems(); // Use the addToCart function from the hook

  const [isCartOpen, setIsCartOpen] = useState(false);

  // Assuming there is an interface for your product/item
interface ProductItem {
  databaseId: number;
  // Other properties...
}

const handleAddToCart = (item: ProductItem) => {
  // Use the addToCart function from the hook
  addToCartHook(item);

  // Add item to WooCommerce cart using GraphQL mutation
  addToCart(item.databaseId, 1); // Assuming quantity is 1, adjust as needed
};

  useEffect(() => {
    // Open the cart when the cart is updated
    if (cart.length > 0) {
      setIsCartOpen(true);
    }
  }, [cart]);

  const handleCloseCart = () => {
    setIsCartOpen(false);
  };

  return (

字符串
这里是hook useCartItems:

export const useCartItems = () => {
  
  // Load cart from localStorage on hook initialization
  const initialCart = JSON.parse(localStorage.getItem('cart')) || [];
  const [cart, setCart] = useState(initialCart);

  // Save cart to localStorage whenever it changes
  useEffect(() => {
    localStorage.setItem('cart', JSON.stringify(cart));
  }, [cart]);

  // Function to add an item to the cart
  const addToCart = (item) => {
    setCart([...cart, item]);
  };

  // Function to clear the entire cart
  const clearCart = () => {
    setCart([]);
  };

  // Function to remove a specific item from the cart
  const removeFromCart = (itemId) => {
    const updatedCart = cart.filter((item) => item.id !== itemId);
    setCart(updatedCart);
  };

  // Calculate cart count
  const cartCount = cart.length;

  return {
    cart,
    cartCount,
    addToCart,
    clearCart,
    removeFromCart,
  };
};


这个钩子可以工作并检索购物车中的项目,但问题是这部分函数:constinitialCart = JSON.parse(localStorage.getItem('cart'))||[的];
这个工作,但nextjs每次返回错误:

ReferenceError: localStorage is not defined
    at useCartItems (./lib/woocommerce/index.ts:454:36)
    at Navbar (./components/layout/navbar/index.tsx:43:96)
  459 |
  460 |   // Load cart from localStorage on hook initialization
> 461 |   const initialCart = JSON.parse(localStorage.getItem('cart')) || [];


我不确定我是否应该这样写,或者可能有另一种解决方案。

ckocjqey

ckocjqey1#

你正在使用pages route,它首先在服务器端呈现页面,本地存储在那里无法访问,因此得到错误。你已经使它有条件,例如使用useEffect或其他技术,所以它只在客户端运行时运行。所以你可以这样修改你的钩子来获得所需的功能:

**解决方案一:**使用额外的useEffect

export const useCartItems = () => {

// Load cart from localStorage on hook initialization
   const [cart, setCart] = useState([]);

   useEffect(() => {
    setCart(JSON.parse(localStorage.getItem('cart')))
  }, []);

 // Save cart to localStorage whenever it changes
 useEffect(() => {
  localStorage.setItem('cart', JSON.stringify(cart));
  }, [cart]);

// Function to add an item to the cart
   const addToCart = (item) => {
   setCart([...cart, item]);
 };

 // Function to clear the entire cart
 const clearCart = () => {
   setCart([]);
  };

 // Function to remove a specific item from the cart
 const removeFromCart = (itemId) => {
   const updatedCart = cart.filter((item) => item.id !== itemId);
   setCart(updatedCart);
 };

 // Calculate cart count
 const cartCount = cart.length;

  return {
   cart,
   cartCount,
   addToCart,
   clearCart,
   removeFromCart,
   };
  };

字符串

解决方案二:使用相同的useEffect,但在第一次渲染时设置

export const useCartItems = () => {

// Load cart from localStorage on hook initialization
   const [cart, setCart] = useState([]);
   const firstRender=useRef(true)

 // Save cart to localStorage whenever it changes
 useEffect(() => {
 if(firstRender.current){
    setCart(JSON.parse(localStorage.getItem('cart')))
    fristRender.current=false;
  }else{
  localStorage.setItem('cart', JSON.stringify(cart));}
  }, [cart]);

// Function to add an item to the cart
   const addToCart = (item) => {
   setCart([...cart, item]);
 };

 // Function to clear the entire cart
 const clearCart = () => {
   setCart([]);
  };

 // Function to remove a specific item from the cart
 const removeFromCart = (itemId) => {
   const updatedCart = cart.filter((item) => item.id !== itemId);
   setCart(updatedCart);
 };

 // Calculate cart count
 const cartCount = cart.length;

  return {
   cart,
   cartCount,
   addToCart,
   clearCart,
   removeFromCart,
   };
  };

相关问题