2

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?

7
  • 3
    What is the error? Commented Apr 18, 2018 at 14:20
  • 3
    remove semicolon after abc: sessionStorage.getItem('testkey'); Commented Apr 18, 2018 at 14:21
  • In your example you can just set the abc state to the test value. There is no benefit writing it to the storage. But say, you get the value from somewhere else then you can set it like that in a function and get in your constructor. Then your approach would be valid. Commented Apr 18, 2018 at 14:22
  • What error did you get? Which line caused the error? Commented Apr 18, 2018 at 14:33
  • I have updated the question, please check and sorry for the delay. Commented Apr 18, 2018 at 20:04

1 Answer 1

1

Im still not too sure what you mean but you definitely have to use this.setState().

this function accepts json {'key':'value'} once set it updates the state. You dont actually have to store a function within a state.

I dont know if this was a thing where you use getters and setters. Set variable values using setState then retrieve them using this.state.[variable_name].

Hope this helps.

class Session extends Component { constructor(props){ super(props); this.setValue = this.setValue.bind(this); this.state = {}; } setValue(key, value){ let data = {}; data[key] = value; this.setState(data); } render() { let session = this.state.session; return ( <div > <div>{ session }</div> <input onClick={ ()=> this.setValue('session','Hello') } type="button" value="Click Me" /> </div> ); } } export default Session; 

Happy coding.

Sign up to request clarification or add additional context in comments.

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.