A continuation of HomeBox the inventory and organization system built for the Home User
fix(frontend): fix mis-matched state errors (#9)
Hayden90813abf76f6
diff --git a/frontend/components/Form/TextArea.vue b/frontend/components/Form/TextArea.vueindex 1157f11b..0580f8e0 100644--- a/frontend/components/Form/TextArea.vue+++ b/frontend/components/Form/TextArea.vue@@ -60,7 +60,6 @@}onUpdated(() => {- console.log("updated");if (props.inline) {setHeight();}diff --git a/frontend/components/Item/CreateModal.vue b/frontend/components/Item/CreateModal.vueindex 4d8a1234..ffc192a6 100644--- a/frontend/components/Item/CreateModal.vue+++ b/frontend/components/Item/CreateModal.vue@@ -27,6 +27,8 @@<script setup lang="ts">import { ItemCreate, LocationOut } from "~~/lib/api/types/data-contracts";+ import { useLabelStore } from "~~/stores/labels";+ import { useLocationStore } from "~~/stores/locations";const props = defineProps({modelValue: {@@ -66,15 +68,11 @@const api = useUserApi();const toast = useNotifier();- const { data: locations } = useAsyncData(async () => {- const { data } = await api.locations.getAll();- return data.items;- });+ const locationsStore = useLocationStore();+ const locations = computed(() => locationsStore.locations);- const { data: labels } = useAsyncData(async () => {- const { data } = await api.labels.getAll();- return data.items;- });+ const labelStore = useLabelStore();+ const labels = computed(() => labelStore.labels);async function create() {if (!form.location) {diff --git a/frontend/components/Location/CreateModal.vue b/frontend/components/Location/CreateModal.vueindex fe52772e..f854c3ca 100644--- a/frontend/components/Location/CreateModal.vue+++ b/frontend/components/Location/CreateModal.vue@@ -62,9 +62,7 @@if (data) {toast.success("Location created");- navigateTo(`/location/${data.id}`);}-reset();}</script>diff --git a/frontend/composables/use-api.ts b/frontend/composables/use-api.tsindex 2a51fd7d..4eb753fe 100644--- a/frontend/composables/use-api.ts+++ b/frontend/composables/use-api.ts@@ -3,6 +3,22 @@ import { UserApi } from "~~/lib/api/user";import { Requests } from "~~/lib/requests";import { useAuthStore } from "~~/stores/auth";+export type Observer = {+ handler: (r: Response) => void;+};++export type RemoveObserver = () => void;++const observers: Record<string, Observer> = {};++export function defineObserver(key: string, observer: Observer): RemoveObserver {+ observers[key] = observer;++ return () => {+ delete observers[key];+ };+}+function logger(r: Response) {console.log(`${r.status} ${r.url} ${r.statusText}`);}@@ -23,5 +39,9 @@ export function useUserApi(): UserApi {}});+ for (const [_, observer] of Object.entries(observers)) {+ requests.addResponseInterceptor(observer.handler);+ }+return new UserApi(requests);}diff --git a/frontend/composables/use-events.ts b/frontend/composables/use-events.tsnew file mode 100644index 00000000..3c1af072--- /dev/null+++ b/frontend/composables/use-events.ts@@ -0,0 +1,38 @@+export enum EventTypes {+ // ClearStores event is used to inform the stores that _all_ the data they are using+ // is now out of date and they should refresh - This is used when the user makes large+ // changes to the data such as bulk actions or importing a CSV file+ ClearStores,+}++export type EventFn = () => void;++export interface IEventBus {+ on(event: EventTypes, fn: EventFn, key: string): void;+ off(event: EventTypes, key: string): void;+ emit(event: EventTypes): void;+}++class EventBus implements IEventBus {+ private listeners: Record<EventTypes, Record<string, EventFn>> = {+ [EventTypes.ClearStores]: {},+ };++ on(event: EventTypes, fn: EventFn, key: string): void {+ this.listeners[event][key] = fn;+ }++ off(event: EventTypes, key: string): void {+ delete this.listeners[event][key];+ }++ emit(event: EventTypes): void {+ Object.values(this.listeners[event]).forEach(fn => fn());+ }+}++const bus = new EventBus();++export function useEventBus(): IEventBus {+ return bus;+}diff --git a/frontend/layouts/home.vue b/frontend/layouts/home.vueindex 634897bd..9f0adc71 100644--- a/frontend/layouts/home.vue+++ b/frontend/layouts/home.vue@@ -7,3 +7,63 @@</main></div></template>++<script lang="ts" setup>+ import { useItemStore } from "~~/stores/items";+ import { useLabelStore } from "~~/stores/labels";+ import { useLocationStore } from "~~/stores/locations";+ /**+ * Store Provider Initialization+ */++ const labelStore = useLabelStore();+ const reLabel = /\/api\/v1\/labels\/.*/gm;+ const rmLabelStoreObserver = defineObserver("labelStore", {+ handler: r => {+ if (r.status === 201 || r.url.match(reLabel)) {+ labelStore.refresh();+ }+ console.debug("labelStore handler called by observer");+ },+ });++ const locationStore = useLocationStore();+ const reLocation = /\/api\/v1\/locations\/.*/gm;+ const rmLocationStoreObserver = defineObserver("locationStore", {+ handler: r => {+ if (r.status === 201 || r.url.match(reLocation)) {+ locationStore.refresh();+ }+ console.debug("locationStore handler called by observer");+ },+ });++ const itemStore = useItemStore();+ const reItem = /\/api\/v1\/items\/.*/gm;+ const rmItemStoreObserver = defineObserver("itemStore", {+ handler: r => {+ if (r.status === 201 || r.url.match(reItem)) {+ itemStore.refresh();+ }+ console.debug("itemStore handler called by observer");+ },+ });++ const eventBus = useEventBus();+ eventBus.on(+ EventTypes.ClearStores,+ () => {+ labelStore.refresh();+ itemStore.refresh();+ locationStore.refresh();+ },+ "stores"+ );++ onUnmounted(() => {+ rmLabelStoreObserver();+ rmLocationStoreObserver();+ rmItemStoreObserver();+ eventBus.off(EventTypes.ClearStores, "stores");+ });+</script>diff --git a/frontend/pages/home.vue b/frontend/pages/home.vueindex 599cf501..ae6d8c1f 100644--- a/frontend/pages/home.vue+++ b/frontend/pages/home.vue@@ -1,4 +1,8 @@<script setup lang="ts">+ import { useItemStore } from "~~/stores/items";+ import { useLabelStore } from "~~/stores/labels";+ import { useLocationStore } from "~~/stores/locations";+definePageMeta({layout: "home",});@@ -8,20 +12,14 @@const api = useUserApi();- const { data: locations } = useAsyncData("locations", async () => {- const { data } = await api.locations.getAll();- return data.items;- });+ const itemsStore = useItemStore();+ const items = computed(() => itemsStore.items);- const { data: labels } = useAsyncData("labels", async () => {- const { data } = await api.labels.getAll();- return data.items;- });+ const locationStore = useLocationStore();+ const locations = computed(() => locationStore.locations);- const { data: items } = useAsyncData("items", async () => {- const { data } = await api.items.getAll();- return data.items;- });+ const labelsStore = useLabelStore();+ const labels = computed(() => labelsStore.labels);const totalItems = computed(() => items.value?.length || 0);const totalLocations = computed(() => locations.value?.length || 0);@@ -67,6 +65,8 @@importRef.value.click();}+ const eventBus = useEventBus();+async function submitCsvFile() {importLoading.value = true;@@ -81,6 +81,8 @@importLoading.value = false;importCsv.value = null;importRef.value.value = null;++ eventBus.emit(EventTypes.ClearStores);}</script>diff --git a/frontend/pages/item/[id]/edit.vue b/frontend/pages/item/[id]/edit.vueindex 34286d07..afc5d88a 100644--- a/frontend/pages/item/[id]/edit.vue+++ b/frontend/pages/item/[id]/edit.vue@@ -1,5 +1,7 @@<script setup lang="ts">import { ItemUpdate } from "~~/lib/api/types/data-contracts";+ import { useLabelStore } from "~~/stores/labels";+ import { useLocationStore } from "~~/stores/locations";definePageMeta({layout: "home",@@ -12,17 +14,13 @@const itemId = computed<string>(() => route.params.id as string);- const { data: locations } = useAsyncData(async () => {- const { data } = await api.locations.getAll();- return data.items;- });+ const locationStore = useLocationStore();+ const locations = computed(() => locationStore.locations);- const { data: labels } = useAsyncData(async () => {- const { data } = await api.labels.getAll();- return data.items;- });+ const labelStore = useLabelStore();+ const labels = computed(() => labelStore.labels);- const { data: item } = useAsyncData(async () => {+ const { data: item, refresh } = useAsyncData(async () => {const { data, error } = await api.items.get(itemId.value);if (error) {toast.error("Failed to load item");@@ -32,6 +30,9 @@return data;});+ onMounted(() => {+ refresh();+ });async function saveItem() {const payload: ItemUpdate = {diff --git a/frontend/pages/item/[id]/index.vue b/frontend/pages/item/[id]/index.vueindex b8b23173..a6196070 100644--- a/frontend/pages/item/[id]/index.vue+++ b/frontend/pages/item/[id]/index.vue@@ -19,8 +19,6 @@}return data;});-- // Trigger Refresh on navigateonMounted(() => {refresh();});diff --git a/frontend/stores/items.ts b/frontend/stores/items.tsnew file mode 100644index 00000000..8f973c43--- /dev/null+++ b/frontend/stores/items.ts@@ -0,0 +1,33 @@+import { defineStore } from "pinia";+import { ItemOut } from "~~/lib/api/types/data-contracts";++export const useItemStore = defineStore("items", {+ state: () => ({+ allItems: null as ItemOut[] | null,+ client: useUserApi(),+ }),+ getters: {+ /**+ * items represents the items that are currently in the store. The store is+ * synched with the server by intercepting the API calls and updating on the+ * response.+ */+ items(state): ItemOut[] {+ if (state.allItems === null) {+ Promise.resolve(this.refresh());+ }+ return state.allItems;+ },+ },+ actions: {+ async refresh(): Promise<ItemOut[]> {+ const result = await this.client.items.getAll();+ if (result.error) {+ return result;+ }++ this.allItems = result.data.items;+ return result;+ },+ },+});diff --git a/frontend/stores/labels.ts b/frontend/stores/labels.tsnew file mode 100644index 00000000..651bb49b--- /dev/null+++ b/frontend/stores/labels.ts@@ -0,0 +1,33 @@+import { defineStore } from "pinia";+import { LabelOut } from "~~/lib/api/types/data-contracts";++export const useLabelStore = defineStore("labels", {+ state: () => ({+ allLabels: null as LabelOut[] | null,+ client: useUserApi(),+ }),+ getters: {+ /**+ * labels represents the labels that are currently in the store. The store is+ * synched with the server by intercepting the API calls and updating on the+ * response.+ */+ labels(state): LabelOut[] {+ if (state.allLabels === null) {+ Promise.resolve(this.refresh());+ }+ return state.allLabels;+ },+ },+ actions: {+ async refresh(): Promise<LabelOut[]> {+ const result = await this.client.labels.getAll();+ if (result.error) {+ return result;+ }++ this.allLabels = result.data.items;+ return result;+ },+ },+});diff --git a/frontend/stores/locations.ts b/frontend/stores/locations.tsnew file mode 100644index 00000000..e677e08f--- /dev/null+++ b/frontend/stores/locations.ts@@ -0,0 +1,33 @@+import { defineStore } from "pinia";+import { LocationCount } from "~~/lib/api/types/data-contracts";++export const useLocationStore = defineStore("locations", {+ state: () => ({+ allLocations: null as LocationCount[] | null,+ client: useUserApi(),+ }),+ getters: {+ /**+ * locations represents the locations that are currently in the store. The store is+ * synched with the server by intercepting the API calls and updating on the+ * response+ */+ locations(state): LocationCount[] {+ if (state.allLocations === null) {+ Promise.resolve(this.refresh());+ }+ return state.allLocations;+ },+ },+ actions: {+ async refresh(): Promise<LocationCount[]> {+ const result = await this.client.locations.getAll();+ if (result.error) {+ return result;+ }++ this.allLocations = result.data.items;+ return result;+ },+ },+});