Make food a global store
This commit is contained in:
@@ -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>
|
||||
|
@@ -21,14 +21,6 @@
|
||||
label: 'Home',
|
||||
href: '/'
|
||||
},
|
||||
{
|
||||
label: 'IPC',
|
||||
href: '/#IPC'
|
||||
},
|
||||
{
|
||||
label: 'Versions',
|
||||
href: '/#versions'
|
||||
}
|
||||
]
|
||||
</script>
|
||||
|
||||
|
@@ -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)
|
||||
foodStore.update((food) => {
|
||||
food.push(event.detail)
|
||||
food = food
|
||||
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>
|
||||
|
15
src/lib/store/foodStore.ts
Normal file
15
src/lib/store/foodStore.ts
Normal 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()
|
Reference in New Issue
Block a user