skip to Main Content

I am working on a showcase website for an alcohol brand and I would like when the site is initialized, a component (a modal that i already create) is displayed for the user’s first visit, but not for the following.

My component (legalAge) is a modal that the purpose is to ask if the user is major ^^

my component

where i would like to put it conditionnaly

I would therefore like to create a variable in the form of a bolean in local storage but I don’t really know how to go about it.

i mean i know create the information in the local Storage but i don’t know how to use it…

I know that this practice is not very reliable in terms of security but I will put up with it for the moment

2

Answers


  1. here is how I do it.

    when the component is first rendered look in local storage for your age key. if found set it.

    then whenever the age changes the use effect keeps your local storage in sync.

      const LOCAL_STORAGE_KEY_AGE = 'age';
    
      const [age, setAge] = useState(() => {
        const storedAge = localStorage.getItem(LOCAL_STORAGE_KEY_AGE);
        return storedAge !== null ? JSON.parse(storedAge) : false;
      });
    
      useEffect(() => {
        localStorage.setItem(LOCAL_STORAGE_KEY_AGE, JSON.stringify(storedAge));
      }, [storedAge]);
    
    Login or Signup to reply.
  2. In your LegalAge Modal, set your localStorage in the onClose function as follows:

    const onClose = () => localStorage.setItem("legal_age", JSON.stringify(true));
    

    In your Home component, proceed to get legal_age from localStorage:

    const isLegal = JSON.parse(localStorage.getItem("legal_age"));
    

    Then proceed to use the isLegal variable conditionally by using ternary operators or if-else statements

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