Skip to content

Commit

Permalink
init cart open state hook (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
julianbenegas authored Nov 1, 2022
1 parent 85c4393 commit 2d371f2
Show file tree
Hide file tree
Showing 4 changed files with 315 additions and 5 deletions.
2 changes: 1 addition & 1 deletion internal/tsconfig/react-library.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"extends": "./base.json",
"compilerOptions": {
"jsx": "react-jsx",
"lib": ["ES2015"],
"lib": ["dom", "ES2015"],
"module": "ESNext",
"target": "es6",
"strict": true
Expand Down
83 changes: 83 additions & 0 deletions packages/hooks/src/helpers/use-cart-open-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import * as React from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";

let isOpenCache = false;
let syncedWithQueryParam = false;

export type UseCartOpenStateOptions = {
syncWithQueryParam?: boolean | { key: string };
};

export const useCartOpenState = ({
syncWithQueryParam,
}: UseCartOpenStateOptions) => {
const queryClient = useQueryClient();

const queryParamKey = React.useMemo(() => {
if (syncWithQueryParam === true) {
return "cart";
}
if (typeof syncWithQueryParam === "object") {
return syncWithQueryParam.key;
}
return null;
}, [syncWithQueryParam]);

const { data: isOpen } = useQuery(["cart-open-state"], () => {
if (syncWithQueryParam && !syncedWithQueryParam) return undefined;
return isOpenCache;
});

const applyCache = React.useCallback(() => {
queryClient.setQueriesData(["cart-open-state"], isOpenCache);
}, [queryClient]);

const open = React.useCallback(() => {
isOpenCache = true;
applyCache();

if (queryParamKey) {
const url = new URL(window.location.href);
url.searchParams.set(queryParamKey, "open");
window.history.replaceState({}, "", url.toString());
}
}, [queryParamKey, applyCache]);

const close = React.useCallback(() => {
isOpenCache = false;
applyCache();

if (queryParamKey) {
const url = new URL(window.location.href);
url.searchParams.delete(queryParamKey);
window.history.replaceState({}, "", url.toString());
}
}, [queryParamKey, applyCache]);

const toggle = React.useCallback(() => {
isOpenCache = !isOpenCache;
applyCache();

if (queryParamKey) {
const url = new URL(window.location.href);
if (isOpenCache) {
url.searchParams.set(queryParamKey, "open");
} else {
url.searchParams.delete(queryParamKey);
}
window.history.replaceState({}, "", url.toString());
}
}, [queryParamKey, applyCache]);

React.useEffect(() => {
if (queryParamKey) {
const urlParams = new URLSearchParams(window.location.search);
const value = urlParams.get(queryParamKey);
isOpenCache = value === "open";
syncedWithQueryParam = true;
applyCache();
}
}, [queryParamKey, applyCache]);

return { isOpen, open, close, toggle };
};
10 changes: 10 additions & 0 deletions packages/hooks/src/storefront-hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
QueryClientProvider,
QueryClientProviderProps,
} from "@tanstack/react-query";
import * as cartOpenState from "./helpers/use-cart-open-state";

import * as addLines from "./mutations/add-lines";
import * as removeLines from "./mutations/remove-lines";
Expand Down Expand Up @@ -77,6 +78,7 @@ export function createStorefrontHooks<
createCartIfNotFound,
queryClientConfig,
extraHooks,
cartOpenStateOptions,
}: {
cartLocalStorageKey: string;
fetchers: {
Expand All @@ -85,6 +87,7 @@ export function createStorefrontHooks<
mutators: StorefrontMutators<NoInfer<Cart>>;
createCartIfNotFound?: boolean;
queryClientConfig?: QueryClientConfig;
cartOpenStateOptions?: cartOpenState.UseCartOpenStateOptions;
extraHooks?: ExtraHooks;
}) {
const queryClient = new QueryClient(queryClientConfig);
Expand All @@ -94,6 +97,7 @@ export function createStorefrontHooks<
// @ts-ignore
return <QueryClientProvider {...props} client={queryClient} />;
},
// QUERIES
useCartQuery: (options?: cartQuery.UseCartQueryUserOptions<Cart>) => {
return cartQuery.useCartQuery({
cartLocalStorageKey,
Expand All @@ -106,6 +110,7 @@ export function createStorefrontHooks<
},
});
},
// MUTATIONS
useOptimisticCartUpdate: () => {
return cartQuery.useOptimisticCartUpdate<Cart>();
},
Expand Down Expand Up @@ -139,6 +144,11 @@ export function createStorefrontHooks<
options: { ...options },
});
},
// CART OPEN STATE
useCartOpenState: () => {
return cartOpenState.useCartOpenState({ ...cartOpenStateOptions });
},
// EXTRA HOOKS
...(extraHooks as OmitIndexSignature<ExtraHooks>),
};
}
Loading

1 comment on commit 2d371f2

@vercel
Copy link

@vercel vercel bot commented on 2d371f2 Nov 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.