0

I am creating a modal to show if it is the first time the page is being loaded. To store the information I am using local storage.

On my products page I have creatyed a variable for the localStorage item 'firstLoad' which defaults back to true if no result is found. Then I set the localStorage item 'firstLoad' to false. I have logged the variables and this does not change them on the same load (which is what I want) but on the modal component the ternary operator is having the opposite effect.

products.js:

let firstLoad = localStorage.getItem('firstLoad') || true

  const [showModal, setShowModal] = useState(firstLoad)

  useEffect(() => {
    localStorage.setItem('firstLoad', false)
  })
  return (
    <Layout>
      <SEO title="Products" />

      {/* Need to keep an eye on this, having the opposite behaviour to what is expected */}
      <Modal showModal={showModal} setShowModal={setShowModal}>
        <h2>OCD DOE-MAX</h2>
        <p>Available in 3 forms and multiple fragrances, we do one product and do it well.</p>
        <p>Click on any active button to see a description of the type or fragrance</p>
        <button onClick={() => setShowModal(false)}>EXPLORE FRAGRANCES</button>
      </Modal>

modal.js:

const Modal = ({ children, showModal, setShowModal }) => {

    const modalSpring = useSpring({
        opacity: showModal ? 1 : 0,
        scale: showModal ? 1 : 0.4
    })

    const backdropSpring = useSpring({
        opacity: showModal ? 1 : 0
    })

    return (
        <div className="modal-wrapper">
            <animated.div className="backdrop" style={backdropSpring} onClick={() => setShowModal(false)} />
            <animated.div className="modal" style={modalSpring}>
                <span style={{ display: 'flex', justifyContent: 'center' }}>
                    <button onClick={() => setShowModal(false)} class="exit">X</button>
                </span>
                {children}
            </animated.div>
        </div >

    )
}
Aiden Barrett
  • 329
  • 1
  • 4
  • 11

1 Answers1

1

This was happening because the localStorage item was returned as a string. I reversed this by using JSON.parse() around the localStorage item.

products.js:

let firstLoad = JSON.parse(localStorage.getItem('firstLoad')) || true

  const [showModal, setShowModal] = useState(firstLoad)

  useEffect(() => {
    localStorage.setItem('firstLoad', "false")
  })
Aiden Barrett
  • 329
  • 1
  • 4
  • 11