Skip to content

Commit 692c959

Browse files
committed
save state to LS
1 parent d78cc8d commit 692c959

File tree

4 files changed

+41
-2
lines changed

4 files changed

+41
-2
lines changed

app.vue

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,23 @@
55
</template>
66

77
<script setup lang="ts">
8-
const { locale } = useI18n()
8+
import {useNutrientsStore} from "~/composables/nutrients/nutrients.store";
9+
import {MEALS_LS} from "~/consts/keys";
10+
11+
const { locale, setLocaleCookie } = useI18n()
12+
const nutrientsStore = useNutrientsStore()
913
1014
const rtlNeededLanguages = ['fa']
15+
16+
nutrientsStore.$subscribe((mutation, state) => {
17+
localStorage.setItem(MEALS_LS, JSON.stringify(state))
18+
})
19+
onMounted(()=>{
20+
nutrientsStore.loadFromLS()
21+
})
22+
23+
watch(locale,(value)=>{
24+
setLocaleCookie(value)
25+
})
26+
1127
</script>

composables/nutrients/nutrients.store.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { defineStore } from "pinia";
22
import type {IMeal} from "~/composables/nutrients/nutrients.interface";
3+
import {MEALS_LS} from "~/consts/keys";
34

45
export interface INutrientsStore {
56
meals:IMeal[]
@@ -27,5 +28,20 @@ export const useNutrientsStore = defineStore("nutrients", {
2728
]
2829
}),
2930
getters: {},
30-
actions: {},
31+
actions: {
32+
loadFromLS(){
33+
if(typeof localStorage != "undefined"){
34+
const savedData = localStorage.getItem(MEALS_LS)
35+
if(!savedData || savedData.length <= 0){
36+
return
37+
}
38+
const savedDataParsed:INutrientsStore = JSON.parse(savedData)
39+
if(!(savedDataParsed?.meals.length > 0)){
40+
return
41+
}
42+
43+
this.meals = structuredClone(savedDataParsed.meals)
44+
}
45+
}
46+
},
3147
});

consts/keys.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const MEALS_LS = "dc"

nuxt.config.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ export default defineNuxtConfig({
2020
},
2121
i18n: {
2222
// Module Options
23+
detectBrowserLanguage: {
24+
useCookie: true,
25+
cookieKey: 'dc-lang',
26+
redirectOn: 'root',
27+
fallbackLocale: 'fa'
28+
},
2329
},
2430
css: [
2531
'primevue/resources/themes/aura-light-green/theme.css',

0 commit comments

Comments
 (0)