Skip to content

Commit

Permalink
Issue with SSR and usling local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
Joshua Toy authored and Joshua Toy committed Jun 23, 2024
1 parent bd90b7a commit be80b3f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
10 changes: 10 additions & 0 deletions src/components/CookieConsentBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,26 @@
import { ThemeButton } from "./ThemeButton";
import { Check, X } from "@phosphor-icons/react";
import { useCookieContext } from "@/context/CookieContext";
import { useEffect, useState } from "react";

const CookieConsentBanner = () => {
const { shouldShowBanner, setShouldAllowCookies, setShouldShowBanner } =
useCookieContext();

const [isClientSide, setIsClientSide] = useState(false);

useEffect(() => {
// Ensure accessing localStorage only runs on the client side.
setIsClientSide(true);
}, []);

const onClickButton = (shouldSaveCookies: boolean) => {
setShouldAllowCookies(shouldSaveCookies);
setShouldShowBanner(false);
};

if (!isClientSide) return null;

return (
<div
className={`${
Expand Down
16 changes: 11 additions & 5 deletions src/context/CookieContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,20 @@ export const useCookieContext = () => {
};

export const CookieProvider: FC<CookieProviderProps> = ({ children }) => {
const [shouldAllowCookies, setShouldAllowCookies] = useState(() => {
const storedPrefs = localStorage.getItem("cookiePrefs");
return storedPrefs ? JSON.parse(storedPrefs).shouldAllowCookies : false;
const [shouldAllowCookies, setShouldAllowCookies] = useState<boolean>(() => {
if (typeof window !== "undefined" && window.localStorage) {
const storedPrefs = localStorage.getItem("cookiePrefs");
return storedPrefs ? JSON.parse(storedPrefs).shouldAllowCookies : false;
}
return false;
});

const [shouldShowBanner, setShouldShowBanner] = useState<boolean>(() => {
const storedPrefs = localStorage.getItem("cookiePrefs");
return storedPrefs ? JSON.parse(storedPrefs).shouldShowBanner : true;
if (typeof window !== "undefined" && window.localStorage) {
const storedPrefs = localStorage.getItem("cookiePrefs");
return storedPrefs ? JSON.parse(storedPrefs).shouldShowBanner : true;
}
return true;
});

useEffect(() => {
Expand Down

0 comments on commit be80b3f

Please sign in to comment.