Andrei
Andrei

Reputation: 47

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

I tried to move usage of localStorage out of component but it won't help. I suppose that using local storage somehow changes this.state.interests that they stop being an array.

let interests = ["Музыка", "Компьютеры", "Радио"]
let ListOfInterest = React.createClass({
  getInitialState: function() {
    return {value: '', interests: interests};
  },
  componentWillMount() {
    let local = localStorage.getItem('interests')
    if (local) {
      this.setState({interests: local});
    } else {
      localStorage.setItem('interests', this.state.interests)}
  },
  deleteInterest(key) {
    delete interests[key]
    this.setState(this.state) // without this line the page will not re-render
  },
  addInterest() {
    interests.unshift(this.state.value)
    this.setState({value: ''})
  },
  handleChange(event) {
    this.setState({value: event.target.value})
  },
  render() {
    return <div className="interests">
      <b>Интересы</b>
      <br/>
      {this.state.interests.map((int, index) => {
        return <button onClick={() => {
          this.deleteInterest(index)
        }} key={index} className="btn-interest">{int}</button>
      })}
      <input type='text' placeholder="Add" value={this.state.value} onChange={(e) => this.handleChange(e)}/>
      <button onClick={() => {
        this.addInterest()
      }} className="add">Add interest</button>

    </div>
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Upvotes: 0

Views: 103

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77512

You have several issues in your example

  1. in localStorage.setItem second argument have to be a String, you can not store Array(when you do it, in storage will be string separated by coma because called method toString - [1, 2, 3].toString() ), you need stringify array before set to Storage

    keyValue A DOMString containing the value you want to give the key you are creating/updating.

    localStorage.setItem(
       'interests', JSON.stringify(this.state.interests)
    )
    

    and parse when get value

    let local = JSON.parse(localStorage.getItem('interests'));
    
  2. this.setState(this.state) this is not good way to update state, you need update state like so

    deleteInterest(key) {
      this.setState({
        interests: this.state.interests.filter((el, i) => i !== key)
      })
    },
    
    addInterest() {
      this.setState({ 
        value: '', 
        interests: this.state.interests.concat(this.state.value)
      });
    },
    

Example

Upvotes: 1

Related Questions