Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 983
Joshua Rajandiran Avatar asked Nov 03 '16 11:11

Joshua Rajandiran


People also ask

What is sessionStorage in Reactjs?

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.

How do you set a value in session storage in react?

// Access value associated with the key var item_value = sessionStorage. getItem("item_key"); // Assign value to a key sessionStorage. setItem("item_key", item_value); Note: All values in Session storage will be stored in string format, hence must be parsed to other data types if required.

How does react store data in session?

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data. Here is a simple example of a UserProfile closure that will hold the user's name.

When should I use sessionStorage?

Session storage is a popular choice when it comes to storing data on a browser. It enables developers to save and retrieve different values. Unlike local storage, session storage only keeps data for a particular session. The data is cleared once the user closes the browser window.


2 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 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");
like image 100
mleko Avatar answered Oct 08 '22 04:10

mleko


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 ? (
    <></>):(<></>)}
like image 24
Gabriel Panegrossi Santos Avatar answered Oct 08 '22 03:10

Gabriel Panegrossi Santos