Skip to content

Instantly share code, notes, and snippets.

@mikoscz
Created October 21, 2017 14:56
Show Gist options
  • Save mikoscz/1c6a63d90bc884b1422823f27de2721d to your computer and use it in GitHub Desktop.
Save mikoscz/1c6a63d90bc884b1422823f27de2721d to your computer and use it in GitHub Desktop.
Ember - recipes stored in localStorage
import Service from '@ember/service';
import { computed } from '@ember/object';
export default Service.extend({
init() {
this._super(...arguments);
if (!localStorage.getItem('recipes')) {
localStorage.setItem('recipes', '[]');
}
if (!localStorage.getItem('idCounter')) {
localStorage.setItem('idCounter', '1');
}
},
recipes: computed(function() {
return this._fetchRecipes();
}),
addRecipe(recipe) {
const recipes = this._readFromStorage('recipes');
const newRecipe = {
...recipe,
...this._generateIdObject()
};
const newRecipes = [...recipes, newRecipe];
return this._saveToStorage('recipes', newRecipes)
},
removeRecipe(recipe) {
const recipes = this._readFromStorage('recipes');
const newRecipes = recipes.reject((r) => r.id === recipe.id);
return this._saveToStorage('recipes', newRecipes)
},
_fetchRecipes() {
const storeData = localStorage.getItem('recipes');
return JSON.parse(storeData);
},
_readFromStorage(key) {
const data = localStorage.getItem(key);
return JSON.parse(data);
},
_saveToStorage(key, data) {
const saved = localStorage.setItem(key, JSON.stringify(data))
this.notifyPropertyChange('recipes');
return saved;
},
_generateIdObject() {
const lastId = this._readFromStorage('idCounter');
const id = lastId + 1;
this._saveToStorage('idCounter', id);
return { id };
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment