forked from n0n3br/medium-article-vite-recipe-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.js
57 lines (57 loc) · 1.74 KB
/
store.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { reactive, computed, watch } from "vue";
const storeName = "vite-recipe-book-store";
const id = () => "_" + Math.random().toString(36).substr(2, 9);
const state = reactive(
localStorage.getItem(storeName)
? JSON.parse(localStorage.getItem(storeName))
: {
ingredients: [],
recipes: [],
}
);
watch(state, (value) => localStorage.setItem(storeName, JSON.stringify(value)));
export const useStore = () => ({
ingredients: computed(() =>
state.ingredients.sort((a, b) => a.name.localeCompare(b.name))
),
recipes: computed(() =>
state.recipes
.map((recipe) => ({
...recipe,
ingredients: recipe.ingredients.map((ingredient) =>
state.ingredients.find((i) => i.id === ingredient)
),
}))
.sort((a, b) => a.name.localeCompare(b.name))
),
addIngredient: (ingredient) => {
state.ingredients = [
...state.ingredients,
{ id: id(), name: ingredient },
];
},
removeIngredient: (ingredient) => {
if (
state.recipes.some((recipe) =>
recipe.ingredients.some((i) => i.id === ingredient.id)
)
)
return;
state.ingredients = state.ingredients.filter(
(i) => i.id !== ingredient.id
);
},
addRecipe: (recipe) => {
state.recipes = [
...state.recipes,
{
id: id(),
...recipe,
ingredients: recipe.ingredients.map((i) => i.id),
},
];
},
removeRecipe: (recipe) => {
state.recipes = state.recipes.filter((r) => r.id !== recipe.id);
},
});