Which method is better when reassigning pinia state variables?

35 Views Asked by At

When using pinia in Vue js application, is it better to write the state variables in action function in pinia and switch it in that way, or is it better to import the state variable in the component and change it there? Which method and why? Thanks in advance for the reply!

1)

postStore.js

import {defineStore} from "pinia"
import {ref} from "vue"

export const usePostStore = defineStore("postStore", () => {
    const posts = ref([])

   async function getPosts() {
    const response = await fetch(someUrl);
    posts.value = await response.json().data.posts;
   }

   return {
    posts,
    getPosts
   }
})

Posts.vue

<template>
  
</template>

<script setup lang="ts">
import {onMounted} from "vue"
import {storeToRefs} from "pinia"
import {usePostStore} from "postStore.js"

const postStore = usePostStore()
const {posts} = storeToRefs(postStore)
async function getPosts(){
        const response = await fetch(someUrl);
        const data = await response.json();
        posts.value = data.posts
}

onMounted(() => {
    getPosts()
})
</script>

<style scoped>

</style>

I usually use the second method. But I saw that the first method is also used

1

There are 1 best solutions below

0
Estus Flask On

The concept of global store suggests that it's responsible for state and logic, this is what the option 1 shows.

Option 2 is global state only, it doesn't make use of Pinia actions. This would require to reimplement getPosts in case it's used in several places. This design choice is not justified.