Home > Blockchain >  I save state in a Local storage, but modal appears on initial load for a <1 sec
I save state in a Local storage, but modal appears on initial load for a <1 sec

Time:12-14

I've got a simple cookie policy modal on initial load. I save state in a Local storage, everything works, but modal apperears for <1 second and dissappears.

import React, { useState, useEffect } from "react";
import styled from "@emotion/styled";

const Cookies = () => {
  const [cookie, setCookie] = useState(false);
  useEffect(() => {
    const cookieAgrees = localStorage.getItem("cookieAgree");
    if (cookieAgrees) {
      setCookie(true);
    }
  }, []);

  return (
    <>
      {!cookie && (
        <Modal>
          <Inside>
            By using this website, you agree to our
            <a href="https://www.cookiesandyou.com/" target="noreferrer">
              Cookie Policy
            </a>
            <span
              onClick={() => {
                setCookie(true);
                localStorage.setItem("cookieAgree", true);
              }}
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 14 14"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M1.66669 1.66669L12.3334 12.3334M12.3334 1.66669L1.66664 12.3334"
                  stroke="#A2A3AD"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                ></path>
              </svg>
            </span>
          </Inside>
        </Modal>
      )}
    </>
  );
};

export default Cookies;

How can I make the window not appear for 1 second on the first render?

CodePudding user response:

Because that the default state you set. You're displaying the modal when cookie is false:

{!cookie && (

And initially setting cookie to false:

const [cookie, setCookie] = useState(false);

If the modal should be hidden by default, default it to true:

const [cookie, setCookie] = useState(true);

And change the logic for updating it:

if (!cookieAgrees) {
  setCookie(false);
}

As an aside, you might find it less confusing overall if you use a more meaningful variable name and values. For example, something like this:

const [showModal, setShowModal] = useState(false);

And to use it:

{showModal && (

Then when you update it:

if (!cookieAgrees) {
  setShowModal(true);
}

Names like "show modal" convey a meaning for the true and false values, making it more intuitive to use and update those values accordingly.

  • Related