EditItemQuantityButton.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import LoadingDots from "@components/common/icons/LoadingDots";
  2. import { MinusIcon, PlusIcon } from "@heroicons/react/24/outline";
  3. import { throttle } from "@utils/helper";
  4. import { useAddProduct } from "@utils/hooks/useAddToCart";
  5. import clsx from "clsx";
  6. function SubmitButton({
  7. type,
  8. handleUpdateCart,
  9. pending,
  10. }: {
  11. type: "plus" | "minus";
  12. handleUpdateCart: (_: "plus" | "minus") => void;
  13. pending: boolean;
  14. }) {
  15. return (
  16. <button
  17. aria-disabled={pending}
  18. aria-label={
  19. type === "plus" ? "Increase item quantity" : "Reduce item quantity"
  20. }
  21. className={clsx(
  22. "ease flex h-full cursor-pointer min-w-[36px] max-w-[36px] flex-none items-center justify-center rounded-full px-2 transition-all duration-200 hover:border-neutral-800 hover:opacity-80",
  23. {
  24. "cursor-wait": pending,
  25. "ml-auto": type === "minus",
  26. }
  27. )}
  28. type="button"
  29. onClick={() => handleUpdateCart(type)}
  30. >
  31. {pending ? (
  32. <LoadingDots className="bg-black dark:bg-white" />
  33. ) : type === "plus" ? (
  34. <PlusIcon className="h-4 w-4 dark:text-neutral-100" />
  35. ) : (
  36. <MinusIcon className="h-4 w-4 dark:text-neutral-100" />
  37. )}
  38. </button>
  39. );
  40. }
  41. interface CartItemEdge {
  42. node: {
  43. id: string;
  44. quantity: number;
  45. name: string;
  46. price: number;
  47. };
  48. }
  49. export function EditItemQuantityButton({
  50. item,
  51. type,
  52. }: {
  53. item: CartItemEdge;
  54. type: "plus" | "minus";
  55. }) {
  56. const { onUpdateCart, isUpdateLoading } = useAddProduct();
  57. const handleUpdateCart = throttle((type: "plus" | "minus") => {
  58. let qty = item?.node?.quantity;
  59. if(!isUpdateLoading){
  60. if (type === "plus") {
  61. qty += 1;
  62. } else if (type === "minus") {
  63. qty -= 1;
  64. }
  65. onUpdateCart({
  66. cartItemId: Number(item?.node?.id),
  67. quantity: qty,
  68. });
  69. }
  70. }, 200);
  71. return (
  72. <SubmitButton
  73. handleUpdateCart={handleUpdateCart}
  74. pending={isUpdateLoading}
  75. type={type}
  76. />
  77. );
  78. }