30

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
    try window.sessionStorage.setItem("key" , "value"); Commented Nov 3, 2016 at 11:09
  • 1
    @Kartik_Agarwal Just tried that, its now showing window is not defined Commented Nov 3, 2016 at 11:11
  • you are using server side rendring or client side? Commented Nov 3, 2016 at 11:16
  • Should be using server side Commented Nov 3, 2016 at 11:18
  • After rendering, I would be able to set my sessionStorage but I want to do it before rendering occurs. Commented Nov 3, 2016 at 11:20

3 Answers 3

56

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 https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Example of writing to storage

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

To retrieve item from storage use

window.sessionStorage.getItem("key"); 
Sign up to request clarification or add additional context in comments.

2 Comments

This is an old question, but can you point out that sessionStorage will work when the component has mounted. That is the moment where sessionStorage will be defined.
The answer is correct that it's only available on the client side. However, to properly answer the above question, IMO the answer should indicate that you can leverage this in componentDidMount ... which happens after React component is fully client side. the pattern you'd use is initialize an state variable with a default setting and then update it with the session information once component is mounted.
3

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 ? ( <></>):(<></>)} 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.