Comments (2)
Here's the StateContext.js file updated:
I added a new property for the products, used only for front-end, called orderValue, based on the order in which products were added.
Every time a customer adds or remove a product from the Cart, this property is updated, being responsible for fixing the product's order in the cart.
import React, { createContext, useContext, useState, useEffect } from 'react';
import { toast } from 'react-hot-toast';
const Context = createContext();
export const StateContext = ({ children }) => {
const [showCart, setShowCart] = useState(false);
const [cartItems, setCartItems] = useState([]);
const [totalPrice, setTotalPrice] = useState(0);
const [totalQuantities, setTotalQuantities] = useState(0);
const [qty, setQty] = useState(1);
let foundProduct;
let index;
const onAdd = (product, quantity) => {
index = cartItems.length;
const checkProductInCart = cartItems.find((item) => item._id === product._id);
setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity);
setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);
if(checkProductInCart) {
const updatedCartItems = cartItems.map((cartProduct) => {
if(cartProduct._id === product._id) return {
...cartProduct,
quantity: cartProduct.quantity + quantity
}
})
setCartItems(updatedCartItems);
} else {
product.quantity = quantity;
product.orderValue = index;
setCartItems([...cartItems, { ...product }]);
}
toast.success(`${qty} ${product.name} added to the cart.`);
}
const onRemove = (product) => {
foundProduct = cartItems.find((item) => item._id === product._id);
const newCartItems = cartItems.filter((item) => item._id !== product._id);
index = newCartItems.length
newCartItems.map((item) => {
if(item.orderValue >= foundProduct.orderValue) item.orderValue -= 1
})
setTotalPrice((prevTotalPrice) => prevTotalPrice -foundProduct.price * foundProduct.quantity);
setTotalQuantities(prevTotalQuantities => prevTotalQuantities - foundProduct.quantity);
setCartItems(newCartItems);
}
const toggleCartItemQuanitity = (id, value) => {
foundProduct = cartItems.find((item) => item._id === id)
index = cartItems.findIndex((product) => product._id === id);
const newCartItems = cartItems.filter((item) => item._id !== id)
if(value === 'inc') {
setCartItems([...newCartItems, { ...foundProduct, quantity: foundProduct.quantity + 1 } ]);
setTotalPrice((prevTotalPrice) => prevTotalPrice + foundProduct.price)
setTotalQuantities(prevTotalQuantities => prevTotalQuantities + 1)
} else if(value === 'dec') {
if (foundProduct.quantity > 1) {
setCartItems([...newCartItems, { ...foundProduct, quantity: foundProduct.quantity - 1 } ]);
setTotalPrice((prevTotalPrice) => prevTotalPrice - foundProduct.price)
setTotalQuantities(prevTotalQuantities => prevTotalQuantities - 1)
}
}
}
const incQty = () => {
setQty((prevQty) => prevQty + 1);
}
const decQty = () => {
setQty((prevQty) => {
if(prevQty - 1 < 1) return 1;
return prevQty - 1;
});
}
return (
<Context.Provider
value={{
showCart,
setShowCart,
cartItems,
totalPrice,
totalQuantities,
qty,
incQty,
decQty,
onAdd,
toggleCartItemQuanitity,
onRemove,
setCartItems,
setTotalPrice,
setTotalQuantities
}}
>
{children}
</Context.Provider>
)
}
export const useStateContext = () => useContext(Context);
And here's the Cart.jsx component updated.
We now use the .sort() function to reorder the products every time we have a removal o addition action on it, using the orderValue property created. So now, the products stay fixed on the same order as we add or remove them.
import React, { useRef } from 'react';
import Link from 'next/link';
import { AiOutlineMinus, AiOutlinePlus, AiOutlineLeft, AiOutlineShopping } from 'react-icons/ai';
import { TiDeleteOutline } from 'react-icons/ti';
import toast from 'react-hot-toast';
import { useStateContext } from '../context/StateContext';
import { urlFor } from '../lib/client';
import getStripe from '../lib/getStripe';
const Cart = () => {
const cartRef = useRef();
const { totalPrice, totalQuantities, cartItems, setShowCart, toggleCartItemQuanitity, onRemove } = useStateContext();
const handleCheckout = async () => {
const stripe = await getStripe();
const response = await fetch('/api/stripe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(cartItems),
});
if(response.statusCode === 500) return;
const data = await response.json();
toast.loading('Redirecting...');
stripe.redirectToCheckout({ sessionId: data.id });
}
return (
<div className="cart-wrapper" ref={cartRef}>
<div className="cart-container">
<button
type="button"
className="cart-heading"
onClick={() => setShowCart(false)}>
<AiOutlineLeft />
<span className="heading">Your Cart</span>
<span className="cart-num-items">({totalQuantities} items)</span>
</button>
{cartItems.length < 1 && (
<div className="empty-cart">
<AiOutlineShopping size={150} />
<h3>Your shopping bag is empty</h3>
<Link href="/">
<button
type="button"
onClick={() => setShowCart(false)}
className="btn"
>
Continue Shopping
</button>
</Link>
</div>
)}
<div className="product-container">
{cartItems.length >= 1 && cartItems.sort((a,b) => a.orderValue > b.orderValue ? 1 : -1).map((item) => (
<div className="product" key={item._id}>
<img src={urlFor(item?.image[0])} className="cart-product-image" />
<div className="item-desc">
<div className="flex top">
<h5>{item.name}</h5>
<h4>${item.price}</h4>
</div>
<div className="flex bottom">
<div>
<p className="quantity-desc">
<span className="minus" onClick={() => toggleCartItemQuanitity(item._id, 'dec') }>
<AiOutlineMinus />
</span>
<span className="num" onClick="">{item.quantity}</span>
<span className="plus" onClick={() => toggleCartItemQuanitity(item._id, 'inc') }><AiOutlinePlus /></span>
</p>
</div>
<button
type="button"
className="remove-item"
onClick={() => onRemove(item)}
>
<TiDeleteOutline />
</button>
</div>
</div>
</div>
))}
</div>
{cartItems.length >= 1 && (
<div className="cart-bottom">
<div className="total">
<h3>Subtotal:</h3>
<h3>${totalPrice}</h3>
</div>
<div className="btn-container">
<button type="button" className="btn" onClick={handleCheckout}>
Pay with Stripe
</button>
</div>
</div>
)}
</div>
</div>
)
}
export default Cart
from ecommerce_sanity_stripe.
As we can't make more PR's in this project, I thought it could be helpful for those who are seeing this now.
Hope it helps.
from ecommerce_sanity_stripe.
Related Issues (20)
- const { decQty, incQty, qty, onAdd, setShowCart } = useStateContext(); these variables are undefined in the slug.js file. On printing useStateContext() on console it shows the default value() HOT 3
- > _No description provided._ HOT 1
- "Error: Unable to resolve image URL from source (undefined)" -> [slug].js: image[index] == undefined HOT 3
- Unable to resolve image URL from source (undefined) at 1:28 min HOT 4
- Schema error
- Sup guys if you have any issues with adding products to local storage here is the code or you wanna Margaret to next.js 13 here is the repo
- TypeError: Cannot read properties of undefined (reading 'length') bannerData.length is not fetching from sanity (sanity has 2 products in it's db) HOT 6
- components and indexjs erros HOT 14
- TypeError: Cannot destructure property 'image' of 'product' as it is null. This error happened while generating the page. Any console logs will be displayed in the terminal window. Source pages\product\[slug].js (9:10) @ ProductDetails 7 | 8 | const ProductDetails = ({ product, products }) => { > 9 | const { image, name, details, price } = product ; | ^ 10 | const [index, setIndex] = useState(0); 11 | const { decQty, incQty, qty, onAdd, setShowCart } = useStateContext(); 12 |
- How to link search bar I added the code but when I click on search it is redirecting me and showing 404 Not Found. can you help me plzzz..!
- Help me create menu i'm newbie PLSSSSSS HOT 1
- if i try to add same item after adding another item it says undefiend to all the other items beside newly added one HOT 1
- Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading '0')
- Module parse failed: Unexpected token (1:7) HOT 2
- Server Error Error: Unable to resolve image URL from source (undefined) This error happened while generating the page. Any console logs will be displayed in the terminal window.
- SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data HOT 2
- Adding commas to separate thousands "("comma-separated values" or "comma formatting." )
- not redirecting to stripe page
- 'Shop Now' button not working. TypeError: Cannot destructure property 'image' of 'product' as it is null
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from ecommerce_sanity_stripe.