Skip to content Skip to sidebar Skip to footer

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

  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

Post a Comment for "Why The Code Stops Working When I Start Using Localstorage?"