Skip to content

Commit

Permalink
Update add to cart
Browse files Browse the repository at this point in the history
  • Loading branch information
imranhsayed committed May 8, 2021
1 parent 3446ab8 commit 44eed42
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 105 deletions.
186 changes: 84 additions & 102 deletions src/components/cart/AddToCartButton.js
Original file line number Diff line number Diff line change
@@ -1,119 +1,101 @@
import { useState, useContext } from "react";
import { useQuery, useMutation } from '@apollo/client';
import { AppContext } from "../context/AppContext";
import { getFormattedCart } from "../../functions";
import {useState, useContext} from "react";
import {useQuery, useMutation} from '@apollo/client';
import Link from "next/link";
import { v4 } from 'uuid';
import {v4} from 'uuid';
import cx from 'classnames';

import {AppContext} from "../context/AppContext";
import {getFormattedCart} from "../../functions";
import GET_CART from "../../queries/get-cart";
import ADD_TO_CART from "../../mutations/add-to-cart";

const AddToCart = ( props ) => {

const { product } = props;

const productQryInput = {
clientMutationId: v4(), // Generate a unique id.
productId: product.productId,
};
const AddToCart = (props) => {

const [ cart, setCart ] = useContext( AppContext );
const [ showViewCart, setShowViewCart ] = useState( false );
const [ requestError, setRequestError ] = useState( null );
const {product} = props;

/**
* @TODO will update this in future, when required.
* Handles adding items to the cart.
*
* @return {void}
*/
// const handleAddToCartLocalStorage = () => {
//
// // If component is rendered client side.
// if ( process.browser ) {
//
// let existingCart = localStorage.getItem( 'woo-next-cart' );
//
// // If cart has item(s) already, update existing or add new item.
// if ( existingCart ) {
//
// existingCart = JSON.parse( existingCart );
//
// const qtyToBeAdded = 1;
//
// const updatedCart = updateCart( existingCart, product, qtyToBeAdded );
//
// setCart( updatedCart );
//
// } else {
// /**
// * If No Items in the cart, create an empty array and add one.
// * @type {Array}
// */
// const newCart = addFirstProduct( product );
// setCart( newCart );
// }
//
// // Show View Cart Button
// setShowViewCart( true )
// }
// };
const productQryInput = {
clientMutationId: v4(), // Generate a unique id.
productId: product.productId,
};

// Get Cart Data.
const { data, refetch } = useQuery( GET_CART, {
notifyOnNetworkStatusChange: true,
onCompleted: () => {
const [cart, setCart] = useContext(AppContext);
const [showViewCart, setShowViewCart] = useState(false);
const [requestError, setRequestError] = useState(null);

// Update cart in the localStorage.
const updatedCart = getFormattedCart( data );
localStorage.setItem( 'woo-next-cart', JSON.stringify( updatedCart ) );
// Get Cart Data.
const {data, refetch} = useQuery(GET_CART, {
notifyOnNetworkStatusChange: true,
onCompleted: () => {

// Update cart data in React Context.
setCart( updatedCart );
}
} );
// Update cart in the localStorage.
const updatedCart = getFormattedCart(data);
localStorage.setItem('woo-next-cart', JSON.stringify(updatedCart));

// Add to Cart Mutation.
const [ addToCart, { data: addToCartRes, loading: addToCartLoading, error: addToCartError }] = useMutation( ADD_TO_CART, {
variables: {
input: productQryInput,
},
onCompleted: async () => {
// On Success:
// 1. Make the GET_CART query to update the cart with new values in React context.
await refetch();
// Update cart data in React Context.
setCart(updatedCart);
}
});

// 2. Show View Cart Button
setShowViewCart( true )
},
onError: ( error ) => {
if ( error ) {
setRequestError( error?.graphQLErrors?.[ 0 ]?.message ?? '');
}
}
} );
// Add to Cart Mutation.
const [addToCart, {
data: addToCartRes,
loading: addToCartLoading,
error: addToCartError
}] = useMutation(ADD_TO_CART, {
variables: {
input: productQryInput,
},
onCompleted: () => {
// On Success:
// 1. Make the GET_CART query to update the cart with new values in React context.
refetch();

const handleAddToCartClick = () => {
// handleAddToCartLocalStorage();
setRequestError( null );
addToCart();
};
// 2. Show View Cart Button
setShowViewCart(true)
},
onError: (error) => {
if (error) {
setRequestError(error?.graphQLErrors?.[0]?.message ?? '');
}
}
});

return (
<div>
{/* Add To Cart Loading*/}
{addToCartLoading && <p>Adding to Cart...</p>}
const handleAddToCartClick = async () => {
setRequestError(null);
await addToCart();
};

{/* Check if its an external product then put its external buy link */}
{ "ExternalProduct" === product.__typename ? (
<a href={ product.externalUrl } target="_blank" className="px-3 py-1 rounded-sm mr-3 text-sm border-solid border border-current inline-block hover:bg-purple-600 hover:text-white hover:border-purple-600">Buy now</a>
) :
<button onClick={ handleAddToCartClick } className="px-3 py-1 rounded-sm mr-3 text-sm border-solid border border-current hover:bg-purple-600 hover:text-white hover:border-purple-600">Add to cart</button>
}
{ showViewCart ? (
<Link href="/cart"><button className="px-3 py-1 rounded-sm text-sm border-solid border border-current inline-block hover:bg-purple-600 hover:text-white hover:border-purple-600">View Cart</button></Link>
) : '' }
</div>
);
return (
<div>
{/* Check if its an external product then put its external buy link */}
{"ExternalProduct" === product.__typename ? (
<a href={product?.externalUrl ?? '/'} target="_blank"
className="px-3 py-1 rounded-sm mr-3 text-sm border-solid border border-current inline-block hover:bg-purple-600 hover:text-white hover:border-purple-600">
Buy now
</a>
) :
<button
disabled={addToCartLoading}
onClick={handleAddToCartClick}
className={cx(
'px-3 py-1 rounded-sm mr-3 text-sm border-solid border border-current',
{'hover:bg-purple-600 hover:text-white hover:border-purple-600': !addToCartLoading},
{'opacity-50 cursor-not-allowed': addToCartLoading}
)}
>
{ addToCartLoading ? 'Adding to cart...' : 'Add to cart' }
</button>
}
{showViewCart ? (
<Link href="/cart">
<button
className="px-3 py-1 rounded-sm text-sm border-solid border border-current inline-block hover:bg-purple-600 hover:text-white hover:border-purple-600">View
Cart
</button>
</Link>
) : ''}
</div>
);
};

export default AddToCart;
2 changes: 1 addition & 1 deletion src/components/checkout/CheckoutForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ const CheckoutForm = ({countriesData}) => {
</form>
) : ''}

{/* Show message if Order Sucess*/}
{/* Show message if Order Success*/}
<OrderSuccess response={checkoutResponse}/>
</>
);
Expand Down
2 changes: 1 addition & 1 deletion src/components/checkout/OrderSuccess.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const OrderSuccess = ( props ) => {
<div className="container">
{ 'success' === responseData.result ? (
<div>
<h2>Order no: { responseData.order.orderId } </h2>
<h2>Order no: { responseData.order.orderNumber } </h2>
<p>Status : { responseData.order.status }</p>
</div>
): ''}
Expand Down
3 changes: 2 additions & 1 deletion src/mutations/checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ mutation CHECKOUT_MUTATION( $input: CheckoutInput! ) {
order {
id
orderKey
orderNumber
status
refunds {
nodes {
amount
}
}
status
}
result
redirect
Expand Down
37 changes: 37 additions & 0 deletions src/utils/cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* @TODO will update this in future, when required.
* Handles adding items to the cart.
*
* @return {void}
*/
// const handleAddToCartLocalStorage = () => {
//
// // If component is rendered client side.
// if ( process.browser ) {
//
// let existingCart = localStorage.getItem( 'woo-next-cart' );
//
// // If cart has item(s) already, update existing or add new item.
// if ( existingCart ) {
//
// existingCart = JSON.parse( existingCart );
//
// const qtyToBeAdded = 1;
//
// const updatedCart = updateCart( existingCart, product, qtyToBeAdded );
//
// setCart( updatedCart );
//
// } else {
// /**
// * If No Items in the cart, create an empty array and add one.
// * @type {Array}
// */
// const newCart = addFirstProduct( product );
// setCart( newCart );
// }
//
// // Show View Cart Button
// setShowViewCart( true )
// }
// };

0 comments on commit 44eed42

Please sign in to comment.