Skip to content

Commit

Permalink
move debounce to useDefferedValue hook
Browse files Browse the repository at this point in the history
  • Loading branch information
encryptedDegen committed Oct 28, 2024
1 parent d1482dd commit 0d6e8b9
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 29 deletions.
Binary file modified bun.lockb
Binary file not shown.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"i18next": "^23.11.5",
"i18next-browser-languagedetector": "^8.0.0",
"i18next-http-backend": "^2.5.2",
"lodash.debounce": "^4.0.8",
"million": "^2.6.4",
"next": "^14.1.4",
"next-themes": "^0.3.0",
Expand Down
54 changes: 26 additions & 28 deletions src/contexts/cart-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import {
type Dispatch,
type ReactNode,
type SetStateAction,
useDeferredValue,
} from "react";
import { useAccount } from "wagmi";
import type { Address } from "viem";
import debounce from "lodash.debounce";
import { hexlify } from "#/lib/utilities";

import {
Expand Down Expand Up @@ -129,39 +129,37 @@ export const CartProvider: React.FC<Props> = ({ children }: Props) => {
// }
// }, [serializedCartItems, address]);

const saveCartToLocalStorage = useCallback(
debounce((addr: Address) => {
if (typeof window !== "undefined") {
const serializedCartItems = cartItems.map(
({ listOp, import: platform }) => {
const addressHex = listOp.data.toString("hex");
const address = `0x${addressHex.slice(0, 40)}` as Address; // Adjust based on address length
const tag =
listOp.data.length > 20 ? listOp.data.slice(20).toString("utf8") : undefined;

return {
opcode: listOp.opcode,
version: listOp.version,
address,
tag,
import: platform,
};
},
[cartItems]
);
const defferedCartItems = useDeferredValue(cartItems);

localStorage.setItem("cart", JSON.stringify(serializedCartItems));
localStorage.setItem("cart address", addr);
}
}, 500),
[cartItems]
);
const saveCartToLocalStorage = (addr: Address) => {
if (typeof window !== "undefined") {
const serializedCartItems = defferedCartItems.map(
({ listOp, import: platform }) => {
const addressHex = listOp.data.toString("hex");
const address = `0x${addressHex.slice(0, 40)}` as Address; // Adjust based on address length
const tag = listOp.data.length > 20 ? listOp.data.slice(20).toString("utf8") : undefined;

return {
opcode: listOp.opcode,
version: listOp.version,
address,
tag,
import: platform,
};
},
[cartItems]
);

localStorage.setItem("cart", JSON.stringify(serializedCartItems));
localStorage.setItem("cart address", addr);
}
};

useEffect(() => {
if (!address) return;

saveCartToLocalStorage(address);
}, [address, saveCartToLocalStorage]);
}, [address, defferedCartItems]);

const addCartItem = useCallback(
(item: CartItem) => {
Expand Down

0 comments on commit 0d6e8b9

Please sign in to comment.