Skip to content

Instantly share code, notes, and snippets.

@ryanjyost
Last active June 3, 2022 01:59
Show Gist options
  • Save ryanjyost/918bbf284781885f2a97d85c4a9b3c6a to your computer and use it in GitHub Desktop.
Save ryanjyost/918bbf284781885f2a97d85c4a9b3c6a to your computer and use it in GitHub Desktop.
addItem() with localStorage
addItem() {
// create a new item
const newItem = {
id: 1 + Math.random(),
value: this.state.newItem.slice()
};
// copy current list of items
const list = [...this.state.list];
// add the new item to the list
list.push(newItem);
// update state with new list, reset the new item input
this.setState({
list,
newItem: ""
});
// update localStorage
localStorage.setItem("list", JSON.stringify(list));
localStorage.setItem("newItem", "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment