Search code examples
javascriptvue.jsvuejs3piniavue-reactivity

Query key array not updating with key is changed


I'm running into an issue where my query key array isn't updating when I change a selected warehouse ID in a dropdown menu. As a result, useQuery is using old query data instead of fetching new data for the selected warehouse ID. I'm not sure how to update the query key array when the selected warehouse ID changes, and I was wondering if you could provide any guidance on how to resolve this issue? Thank you!

import { useQuery } from '@tanstack/vue-query'

const fetchTotalSellers = async warehouseId => {
  const res = await axios.get('/analytics/getTotalSellers', {
    params: {
      warehouseId,
    },
  })
  return res.data
}

const userStore = useUserStore() // pinia store
const { data } = useQuery(
  ['analytics', userStore.selectedWarehouse],
  () => fetchTotalSellers(userStore.selectedWarehouse),
  {
    refetchOnWindowFocus: false,
    onSuccess: data => {
      console.log('data', data)
    },
  },
)
// userStore.js
import { defineStore } from 'pinia' 
 export const useUserStore = defineStore('user', { 
   state: () => { 
     return { 
       info: null, 
       isLoggedIn: false, 
       warehouses: [], 
       selectedWarehouse: null, 
     } 
   }, 
  
   getters: { 
     userInfo: state => { 
       return state.info 
     }, 
     getSelectedWarehouse: state => { 
       return state.selectedWarehouse 
     }, 
     getWarehouses: state => { 
       return state.warehouses 
     }, 
   }, 
   actions: { 
     setUser(user) { 
       this.info = user 
       this.isLoggedIn = true 
     }, 
  
     setSelectedWarehouse(warehouseId) { 
       this.selectedWarehouse = warehouseId 
       localStorage.setItem('selected_warehouse', warehouseId) 
     }, 
     logout() { 
       this.token = null 
       this.user = null 
       this.isLoggedIn = false 
       localStorage.removeItem('id_token') 
     }, 
   }, 
 })

Solution

  • Convert store value to ref. It should trigger the refetch when used as query key.

        const userStore = useUserStore()
        const { selectedWarehouse} = storeToRefs(userStore)
    
        const { data } = useQuery(
          ['analytics', selectedWarehouse],
          () => fetchTotalSellers(selectedWarehouse),
          {
            refetchOnWindowFocus: false,
            onSuccess: data => {
              console.log('data', data)
            },
          },
        )