Make food a global store

This commit is contained in:
2024-06-12 09:05:43 +02:00
parent 5ee56a98d0
commit 2d81d03bbd
4 changed files with 29 additions and 19 deletions

View File

@@ -2,6 +2,8 @@
import { type Food, FoodService } from '$lib/database/food'
import { toast } from 'svelte-sonner'
import { createEventDispatcher } from 'svelte'
import type { Err } from '$lib/types'
import { foodStore } from '$lib/store/foodStore'
const dispatch = createEventDispatcher()
@@ -19,7 +21,7 @@
item.food = name.trim()
item.amount = parseInt(amount.trim())
item.description = description.trim()
const [food, err] = await FoodService.Create(item)
const [dbFood, err]: [Food, Err] = await FoodService.Create(item)
name = ''
amount = ''
description = ''
@@ -28,7 +30,10 @@
toast.error(err)
return
}
dispatch('created', food)
foodStore.update((food) => {
food.push(dbFood)
return food
})
}
}
</script>

View File

@@ -21,14 +21,6 @@
label: 'Home',
href: '/'
},
{
label: 'IPC',
href: '/#IPC'
},
{
label: 'Versions',
href: '/#versions'
}
]
</script>

View File

@@ -3,16 +3,14 @@
import { type Food, FoodService } from '$lib/database/food'
import FoodComp from '$components/FoodComp.svelte'
import EmptyFoodComp from '$components/EmptyFoodComp.svelte'
let food: Food[] = []
onMount(async () => {
food = await FoodService.GetAllForDate(new Date());
})
import { foodStore } from '$lib/store/foodStore'
function newFood(event: CustomEvent<Food>) {
console.log(event)
food.push(event.detail)
food = food
foodStore.update((food) => {
food.push(event.detail)
return food
})
}
</script>
@@ -43,8 +41,8 @@
</tr>
</thead>
<tbody>
<EmptyFoodComp on:created={newFood}/>
{#each food as f}
<EmptyFoodComp/>
{#each $foodStore as f}
<FoodComp item="{f}" />
{/each}
</tbody>

View File

@@ -0,0 +1,15 @@
import { type Writable, writable } from 'svelte/store'
import { type Food, FoodService } from '$lib/database/food'
async function createStore(): Promise<Writable<Food[]>> {
const foods = await FoodService.GetAllForDate(new Date())
const { subscribe, update, set } = writable(foods)
return {
subscribe,
update,
set
}
}
export const foodStore = await createStore()