I want to initiate my state using local/session storage. Is this approach valid? I tried but it gives me an error. If not, then how can I retrieve a value from the storage directly to my state?
constructor(props) { super(props); sessionStorage.setItem('testkey','test value') this.state = { abc: sessionStorage.getItem('testkey') } } The error is always undefined.
Also, if I use the other way around, below code works fine
constructor(props) { super(props); this.state = { abc: this.getItems(val) } this.getItems = this.getItems.bind(this); } getItems(value){ let selectedItem = value; return selectedItem; } But when I do this, it doesn't. I just cannot get the value from my session storage.
constructor(props) { super(props); this.state = { abc: this.getItems(val) } this.getItems = this.getItems.bind(this); } getItems(val){ let setItem = sessionStorage.setItem('testkey', val); let getItem = sessionStorage.getItem('testkey'); return getItem; } When I log getItem to my console, it gives me an object. What could possibly be the problem?
abc: sessionStorage.getItem('testkey');