0

This is what I have so far: https://gist.github.com/justgoof9/f6250cdbd615bda139ef8d56375fa12c

So when I add items to the list then when I refresh the browser, I want it to still save. I want to do it with JSON but don't know how. Can anyone help me?

Nischal
  • 35
  • 7
  • Possible duplicate of [Storing Objects in HTML5 localStorage](https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – Randy Casburn May 19 '18 at 17:33
  • Possible duplicate of [Using LocalStorage with React?](https://stackoverflow.com/questions/38423108/using-localstorage-with-react) – bennygenel May 19 '18 at 18:03

2 Answers2

0

Yes you can achieve it by using local storage, so whenever you push something to your to Todo list, save the updated list in local storage and then when you are rendering in the UI use the data that is stored in local storage. Here is a small example to achieve this --> https://www.w3schools.com/html/html5_webstorage.asp Hope this solved your problem.

Jaya Krishna
  • 313
  • 4
  • 14
0

Hi storing objects in LocalStorage is a bit tricky because LocalStorage accepts strings, but JSON.stringify() comes to the rescue! In you function addToList:

addToList = input => {
    let listArray = this.state.lists;

    listArray.push(input);

    this.setState({
      list: listArray,
      userInput: ""
    });
  };

You want to add a LocalStorage call that saves the list from this.state into LocalStorage, like this:

addToList = input => {
    let listArray = this.state.lists;

    listArray.push(input);

    this.setState({
      lists: listArray,
      userInput: ""
    }, () => {
        window.localStorage.setItem('savedList', JSON.stringify(this.state.lists));
    });
  };

And to retrieve it, you need to parse it back into an array/object, like this:

componentDidMount() {
    const list = window.localStorage.getItem('savedList');
    const parsedList = JSON.parse(list);

    this.setState({
        lists: parsedList,
    })
}

Now every new item you add is saved to localStorage and is retrieved on refresh, all that is left is to apply the same logic to removing items, like this:

listOnClick = index => {
    var arr = this.state.lists;
    arr.splice(index, 1);

    this.setState({ lists: arr }, () => {
        window.localStorage.setItem('savedList', JSON.stringify(this.state.lists));
    });
};

You also had a typo in addToList, you were assigning to this.state.list instead of this.state.lists

Antonio Erdeljac
  • 2,974
  • 1
  • 17
  • 24