Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nextjs trying to access local storage before initialization

I’m trying to achieve next: I have sidebar with 2 buttons, contact and profile. whenever user clicks either of them the URL updates to: /?section=clickedItem so user can save state and on refresh can return to that page. to control the state i’m using this code:

checking either query or localstorage to see which component to load

 useEffect(() => {
    if (router.isReady) {
      const sectionFromURL = router.query.section;
      const sectionFromStorage = localStorage.getItem('section');
      const chatFromStorage = localStorage.getItem('chat');
      setCurrentSection(sectionFromURL || sectionFromStorage || 'contacts');
      setSelectedChat(chatFromStorage || null);
    }
  }, [router.isReady]);

Update state in local storage whenever it changes

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  useEffect(() => {
    console.log(currentSection);
    if (router.isReady) {
      localStorage.setItem('section', currentSection);
      router.push({
        pathname: router.pathname,
        query: { section: currentSection },
      });
    }

    if (selectedChat) {
      localStorage.setItem('chat', selectedChat);
    }
  }, [currentSection, selectedChat]);

the problem is next : whenever i visit localhost:3000/?section=contacts , it works fine and loads the selected element. same with profile. however, loading localhost:3000 always defaults to contacts , changes url to that and also writes contacts in the localstorage

problem seems to be this section

const sectionFromStorage = localStorage.getItem('section');
setCurrentSection(sectionFromURL || sectionFromStorage || 'contacts');

currectSection always gets set to ‘contacts’

>Solution :

This is the correct behavior of what you declared in useEffect.

On each first render, all useEffects run.

The first one is checking whether you have a value in url or localStorage and if not you’re setting its value to "contacts"

The second one possibly starts with currentSection as undefined and it is setting the localStorage value to that, then receives a change of the first one which set currentSection to "contacts", runs for a second time and writes it into the storage.

If you want to prevent this from happening, in the second useEffect check whether value of currentSection is undefined, and if not run the effect you want. This will prevent setting "contacts" as the default value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading