Search code examples
gatsby

Key Value not Store in session storage after deploying site in Gatsby


I make my site in gatsby, and I try to sawing a popup form using session storage it works fine in the local server and also it works fine in the development server but when I live on the production server then it does not store key-value in session storage, I write session storage logic in the gatsby-browser.js

enter image description here

above image is result of local development in live it saw empty

gatsby-browser.js

function addPopUp() {
  sessionStorage.setItem('popUpKey', true)
  sessionStorage.setItem('popUpCount', 0)
  sessionStorage.setItem('startTime', 50);
  sessionStorage.setItem('GitexForm', false);
}

window.addEventListener("load", function() { addPopUp() })

function timer() {
  var AA = sessionStorage.getItem('startTime')
  window.setInterval(function () {
    if (AA > 0) {
      AA -= 1;
      sessionStorage.setItem('First', AA);
    }
  }, 1000);
}

window.addEventListener("load",  function() { timer() })

Solution

  • Use a React-based approach instead of dealing with the DOM, as you are doing at:

    window.addEventListener("load", function() { addPopUp() })
    

    You are manipulating the DOM, while React (hence Gatsby) deals with the virtual DOM (vDOM). The changes you do in one of them are not notified in the other one, so you may be losing functionalities and features.

    Try using:

    useEffect(()=>{
      addPopUp()
    }, [])
    

    useEffect with empty deps ([]) is fired once the DOM tree is loaded, which is almost equivalent to the window's load event.

    Further details: