Initializing and using `sessionStorage` in React

I'm currently trying to save an item into sessionStorage before rendering occurs.

My code is something like this:

 componentWillMount() { sessionStorage.setItem("isUserLogged", false); } 

However, it says that "sessionStorage is not defined." How do I use sessionStorage in React before rendering occurs?

7

3 Answers

SessionStorage is not available when using server side rendering (you can mock it but data won't be available to user).

It's available only in browser

Example of writing to storage

window.sessionStorage.setItem("key", "value"); 

To retrieve item from storage use

window.sessionStorage.getItem("key"); 
2

I was using next and used react effect to solve the problem, solved like this:

import React from 'react'; function Cookies() { const [accepted, setAccepted] = React.useState(false); React.useEffect(() => { if (window.sessionStorage.getItem('cookies')) { setAccepted(true); } }, []); function acceptPolicy() { sessionStorage.setItem('cookies', true); setAccepted(true); } return !accepted ? ( <></>):(<></>)} 

The read-only sessionStorage property accesses a session Storage object for the current origin. sessionStorage is similar to localStorage; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like