refactor: global shared state and function (#79)

* refactor: expose i18n instance

* feat: add global app utility function

* refactor: use global utility function

* refactor: avoid undefined when use outside vue

refactor: avoid undefined when use outside vue

* refactor: remove dup code and use util

* refactor: auto fetch option when use store
This commit is contained in:
Methapon Metanipat 2024-11-21 11:55:44 +07:00 committed by GitHub
parent aa79a4ef7d
commit b0136bba4d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 136 additions and 216 deletions

View file

@ -1,4 +1,4 @@
import { ref } from 'vue';
import { ref, watch } from 'vue';
import { defineStore } from 'pinia';
import { useI18n } from 'vue-i18n';
@ -7,7 +7,23 @@ const useOptionStore = defineStore('optionStore', () => {
const globalOption = ref();
const rawOption = ref();
function mapOption(value: string, categoryKey?: string) {
(async () => {
rawOption.value = await fetch('/option/option.json').then((r) => r.json());
_switchOptionLang();
})();
watch(locale, _switchOptionLang);
function _switchOptionLang() {
if (rawOption.value) {
if (locale.value === 'eng') globalOption.value = rawOption.value.eng;
if (locale.value === 'tha') globalOption.value = rawOption.value.tha;
}
}
function mapOption(value: string, categoryKey?: string): string {
if (categoryKey) {
const option = globalOption.value[categoryKey].find(
(opt: { value: string }) => opt.value === value,
@ -25,17 +41,8 @@ const useOptionStore = defineStore('optionStore', () => {
return value;
}
async function fetchOption() {
const resultOption = await fetch('/option/option.json');
rawOption.value = await resultOption.json();
if (locale.value === 'eng') globalOption.value = rawOption.value.eng;
if (locale.value === 'tha') globalOption.value = rawOption.value.tha;
}
return {
globalOption,
fetchOption,
mapOption,
};
});