Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support local storage ? #21

Open
malithmcr opened this issue Jan 2, 2019 · 2 comments
Open

Support local storage ? #21

malithmcr opened this issue Jan 2, 2019 · 2 comments

Comments

@malithmcr
Copy link

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

@sivadass
Copy link
Owner

sivadass commented Jan 3, 2019

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!

@malithmcr
Copy link
Author

Great. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants