skip to Main Content

I’m encountering an issue with sessionStorage in my React app. I’m using the "use client" pragma to ensure certain code runs only on the client side, but I’m still getting a ReferenceError.

Here’s my code:

"use client";

import { useEffect, useState } from "react";
import { ProgressBar } from "staysure-component-library";
import Footer from "../components/organisms/footer/Footer";
import HomePage from "../components/pages/Home/HomePage";
import Styles from "./homePage.module.css";

function Page() {
  const [test, setTest] = useState(false);
  let hideFooter = sessionStorage.getItem("footer") === "true";

  useEffect(() => {
    if (!hideFooter) {
      sessionStorage.setItem("footer", "true");
    }
  }, []);

  return (
    <div className="bg-surface-neutral-option-2">
      <header>
        <ProgressBar value={10} />
      </header>
      <div>
        <HomePage />
        {hideFooter ? null : (
          <footer>
            <Footer />
          </footer>
        )}
      </div>
    </div>
  );
}

export default Page;

2

Answers


  1. error is from here:

    let hideFooter = sessionStorage.getItem("footer") === "true";
    

    client components first gets prerendered on the server to show the non-intearctive page html to the user as quick as possible. during this prerender on the server, sessionStorage is not defined.

    function Page() {
      const [hideFooter, setHideFooter] = useState(false);
    
      useEffect(() => {
        // This code now runs only on the client side, avoiding the ReferenceError
        const footerHidden = sessionStorage.getItem("footer") === "true";
        setHideFooter(footerHidden);
    
        if (!footerHidden) {
          sessionStorage.setItem("footer", "true");
        }
      }, []);
    
    return (
     jsx here
    ) 
    }
    

    this will get rid of the error.

    Login or Signup to reply.
  2.  useEffect(() => {
        // Check if we're in the browser environment
        if (typeof window !== "undefined") {
          const storedFooterState = sessionStorage.getItem("footer");
          if (!storedFooterState) {
            sessionStorage.setItem("footer", "true");
            setHideFooter(true);
          } else {
            setHideFooter(storedFooterState === "true");
          }
        }
      }, []);
    

    this must work I had the same problem with my app running in nextjs this helped me

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search