Why The Code Stops Working When I Start Using Localstorage?
The code below is only working when I remove the componentWillMount that uses localStorage. With usage localStorage it gives a mistake this.state.interests.map is not a function
Solution 1:
You have several issues in your example
in
localStorage.setItemsecond argument have to be aString, you can not storeArray(when you do it, in storage will be string separated by coma because called methodtoString-[1, 2, 3].toString()), you needstringifyarray before set to StoragekeyValueA DOMString containing the value you want to give the key you are creating/updating.localStorage.setItem( 'interests', JSON.stringify(this.state.interests) )and
parsewhen get valuelet local = JSON.parse(localStorage.getItem('interests'));this.setState(this.state)this is not good way to update state, you need update state like sodeleteInterest(key) { this.setState({ interests: this.state.interests.filter((el, i) => i !== key) }) }, addInterest() { this.setState({ value: '', interests: this.state.interests.concat(this.state.value) }); },
Post a Comment for "Why The Code Stops Working When I Start Using Localstorage?"