Vue 3 pinia getters not reactive in the <script> tag

47 Views Asked by At

I have a vue 3 frontend that fetches a todo array and stores it in a pinia store. The store uses getters retrieve a filtered array of todos.

When rendering todosStore.getIncompleteTodosWithinOneDay.length in the vue template, I can see that the value is updating properly in the template every time a new todo item is added. However, in the script setup section, I cannot get the todosStore.getIncompleteTodosWithinOneDay.length to react to new todo items.

I expect the console.log() and the data in the chartConfig to get an updated value of length, when a new item is added.

Here is the vue component:

<script setup>
import { useTodos } from '@/stores/todosStore';

const todosStore = useTodos()
await todosStore.fetchAllTodos()

ChartJS.register(ArcElement, Tooltip, Legend)

console.log(todosStore.getIncompleteTodosWithinOneDay.length) // expected to be called again with a new value when todo item is added

const chartConfig = {
    labels: ['Overdue', 'Today', 'Next Three Days'],
    datasets: [
        {
            backgroundColor: ['#DD1B16', '#00D8FF', '#41B883'],
            data: [3, 
todosStore.getIncompleteTodosWithinOneDay.length, // expect this to update as well
2]
        }
    ]
}

const chartOptions = {
    responsive: true,
    maintainAspectRatio: false
}
</script>

<template>
    <Doughnut :data="chartConfig" :options="chartOptions"></Doughnut>
    {{ todosStore.getIncompleteTodosWithinOneDay.length }} // this value gets updated successfully whenever a new todo item is added
</template>

todoStore.js:

export const useTodos = defineStore("todos", {
    state: () => ({
        todos: []
    }),
    actions: {
        async fetchAllTodos() {
            try {
                const res = await axios.get(`${TODOS_URI}`)
                this.todos = res.data
            } catch (error) {
                console.error(`Failed operation: fetchAllTodos()`)
                console.error(error)
            }
        },
        async addTodo(data) {
            await this.todos.push(data)
        }
    },
    getters: {
        getIncompleteTodosWithinOneDay: (state) => {
            return state.todos.filter(
                (todo) => {
                    if (todo.completed) {
                        return
                    }
                    const diffDays = getTimeDiffFromNowOfTodo(todo)
                    if (isNaN(diffDays)) {
                        return
                    }
                    if (deadlineInOneDay(todo)) {
                        return todo
                    }
                }
            )
        },
    }
})
1

There are 1 best solutions below

2
Ndiaye Sire KANE On

persist: true, before the action:{}

So your data will persist in the localStorage