react-shopping-cart icon indicating copy to clipboard operation
react-shopping-cart copied to clipboard

Support local storage ?

Open malithmcr opened this issue 6 years ago • 2 comments

Can you make it support local storage? because now if we refresh after adding to cart, all my items are cleared.

malithmcr avatar Jan 02 '19 11:01 malithmcr

Yeah we can do it, for time being, you can refer this component from one of my other project:

componentDidMount() {
    this.hydrateStateWithLocalStorage();
  }

  handleAddNew = (id, message, isCompleted) => {
    let newNote = { id, message, isCompleted };
    let notes = [...this.state.notes, newNote];
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
  }

  handleStatusUpdate = (id, isCompleted) => {
    let notes = [...this.state.notes];
    let index = notes.findIndex(item => item.id === id);
    notes[index].isCompleted = isCompleted;
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
    console.log(JSON.parse(localStorage.getItem('notes')), null, 2);
  }

  handleMessageUpdate = (id, message) => {
    let notes = [...this.state.notes];
    let index = notes.findIndex(item => item.id === id);
    notes[index].message = message;
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
  }

  handleDelete = (id) => {
    let notes = [...this.state.notes];
    let index = notes.findIndex(item => item.id === id);
    notes.splice(index, 1);
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
  }

  hydrateStateWithLocalStorage() {
    // for all items in state
    for (let key in this.state) {
      // if the key exists in localStorage
      if (localStorage.hasOwnProperty(key)) {
        // get the key's value from localStorage
        let value = localStorage.getItem(key);

        // parse the localStorage string and setState
        try {
          value = JSON.parse(value);
          this.setState({ [key]: value });
        } catch (e) {
          // handle empty string
          this.setState({ [key]: value });
        }
      }
    }
}

I will update the same feature in react-shopping-cart in few days!

sivadass avatar Jan 03 '19 09:01 sivadass

Great. Thanks

malithmcr avatar Jan 03 '19 09:01 malithmcr