From 3b6bced57a0930df739c91f0f53782552b562ef5 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Fri, 25 Jul 2025 10:48:00 +0700 Subject: [PATCH] fix useStructStore --- .../components/StructureOrgMain.vue | 27 ++++++++-------- src/modules/02_organization/store/chart.ts | 31 +++++++++++++++++++ 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/src/modules/02_organization/components/StructureOrgMain.vue b/src/modules/02_organization/components/StructureOrgMain.vue index 0cd3704bc..4a6ae377f 100644 --- a/src/modules/02_organization/components/StructureOrgMain.vue +++ b/src/modules/02_organization/components/StructureOrgMain.vue @@ -150,20 +150,21 @@ async function scrollToCenter() { } async function fetchAgencyData(id: string) { + if (!id) return; // ถ้าไม่มี id ให้ return ออกไป + agencyId.value = ""; - await http - .get(config.API.orgByid(id)) - .then((res) => { - const data = res.data.result.data; - agencyData.value = data.map((item: any) => ({ - id: item.orgTreeId, - name: item.orgName, - })); - agencyOp.value = agencyData.value; - }) - .catch((err) => { - messageError($q, err); - }); + try { + const data = await storeOrg.fetchDataTree(id); + console.log(data); + + agencyData.value = data.data.map((item: any) => ({ + id: item.orgTreeId, + name: item.orgName, + })); + agencyOp.value = agencyData.value; + } catch (err) { + messageError($q, err); + } } function onSelectAgency(val: string) { diff --git a/src/modules/02_organization/store/chart.ts b/src/modules/02_organization/store/chart.ts index 8fb92354a..23dff2503 100644 --- a/src/modules/02_organization/store/chart.ts +++ b/src/modules/02_organization/store/chart.ts @@ -1,9 +1,40 @@ import { defineStore } from "pinia"; import { ref } from "vue"; +import http from "@/plugins/http"; +import config from "@/app.config"; + export const useStructStore = defineStore("StructStore", () => { const dataSource = ref(); + const cachedData = ref>({}); + + /** + * ฟังก์ชันดึงข้อมูลโครงสร้าง + * @param keyId id โครงสร้าง + */ + async function fetchDataTree(keyId: string) { + // ตรวจสอบว่ามีข้อมูลใน cache แล้วหรือไม่ + if (cachedData.value[keyId]) { + return cachedData.value[keyId]; + } + + // ถ้าไม่มีข้อมูลใน cache หรือ forceRefresh เป็น true ให้ดึงข้อมูลจาก API + try { + const res = await http.get(config.API.orgByid(keyId)); + const result = res.data.result; + + // เก็บข้อมูลใน cache + cachedData.value[keyId] = result; + + return result; + } catch (error) { + console.error("Error fetching data tree:", error); + return []; + } + } + return { dataSource, + fetchDataTree, }; });