Query key array failing to update when key is modified

Encountering an issue with the query key array not updating when the selected warehouse ID is changed. This causes useQuery to use outdated data instead of fetching new data for the updated warehouse ID. Struggling to figure out how to update the query key array upon selection change, seeking guidance on resolving this matter. Appreciate any assistance provided. 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') 
     }, 
   }, 
 })

Answer №1

Transforming store value into a reference, triggering refetch upon query key usage.

    const userStore = useUserStore()
    const { selectedWarehouse} = storeToRefs(userStore)

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show/Hide Row in Material-UI DataGrid

I need assistance with expanding lines in Material UI. I am trying to create drop-down rows in my table (individually for each row) within a table built using Material UI. Despite researching extensively online, I have been unable to achieve consistent res ...

Rendering tables multiple times using VueJS

I need to display only 5 results from an API call, but currently getting more than that. I attempted using an index, but since it's conditional rendering and some results are skipped, the index isn't a viable solution. Is there a way to assign a ...

Illuminate specific areas of a mapped image upon hovering over text on a webpage

Scenario: There is an image on the page with various mapped areas. A list of text elements is also present on the page. Desired functionality: Hovering over different text items in the list should result in highlighting corresponding areas on the mappe ...

What is the best method for concealing a specific element on the screen using ReactJS?

I'm looking for a way to have text displayed on the screen that is only hidden when a button is pressed, but I'm struggling to figure it out. I had the idea of using useState in this way: const [textVisibility, setTextVisibility] = useState(true) ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

Vue.js - The dissonance between data model and displayed output

Below is a simplified example of my issue: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://unpkg.com/vue/dist/vue.js"></script> ...

Unique 512-character string generated with Node.js

Is it possible to create a string of 512 characters in length that is truly unique? Can the nodejs built-in crypto module be used for this purpose to minimize collisions? Do you think the following sample code can achieve this goal? crypto.randomBytes(51 ...

Navigate to a different page using an AJAX request

Is it possible to use ajax for redirecting to another page? Here's the code I've been working on: <script type="text/javascript"> $(document.body).on('click', '#btnPrintPrev', function() { $.ajax({ url: &apo ...

Leveraging body-parser for capturing an indefinite amount of text fields in node/express

Background In pursuit of my Free Code Camp back end certification, I am embarking on the task of creating a voting application. For detailed information and user stories required for this project, visit this link: Among the user stories is the ability to ...

Experiencing complications when retrieving API information in my React component

There is a json file available: {"area":[{"id":"1","name":"abc","address":"223 "},{"id":"2","name":"xyz","address":"123 "}] I am trying to fetch and display the data in my component using react and redux. Although I have successfully loaded the url with ...

Modify a CSS style with JavaScript or jQuery

Can CSS rules be overwritten using jQuery or JavaScript? Imagine a table with rows categorized by different classes - "names" for persons and "company" for companies. How can we efficiently hide or show specific rows based on these classes? If we have a ...

Who needs a proper naming convention when things are working just fine? What's the point of conventions if they don't improve functionality?

I am a newcomer to the world of JavaScript programming and stumbled upon this example while practicing. <html> <head> <script type="text/javascript"> function changeTabIndex() { document.getElementById('1').tabIndex="3" d ...

Interact with USB drive using electron to both read and write data

I am currently developing an electron project that involves copying files from a computer to USB drives. I need the ability to transfer files and folders to the destination USB drive, as well as determine the amount of free space on the drive. I have expe ...

Interactive game created using JavaScript input

I've scoured the internet for guidance on creating a text-based game that utilizes user input, but all I come across are tutorials focusing on button interactions. What I envision is triggering different responses based on specific user inputs. For i ...

Tips for incorporating a return statement within a network request function that is already returning information pertaining to the request

Is there a way to retrieve the data extracted from within newReq.on('response', (response) => {? var request = require('request'); const cheerio = require('cheerio'); const { app, net, BrowserWindow } = require('elect ...

Having trouble initiating a "curl:localhost:3000" connection, receiving a URI Error message

Recently delving into the realm of node js, I have embarked on a journey to start up a server and experiment with an app designed to trim URLs. However, I find myself at an impasse. Environment: Windows Text Editor: VSCode Below is my code for index.js ...

Having trouble getting Highcharts SVG element to refresh? Looking to incorporate custom freeform drawing features within Highcharts?

I have implemented highchart for graph rendering and utilized the renderer to draw a custom line within the chart. I am looking for a way to recalculate and repaint this path whenever there is a change in data. The framework being used is highcharts-ng alo ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

Exploring the Battle of Efficiency: Stateless Components vs. Class Components in the Age of React Hooks - Determining the Superior Approach

Having delved into various online resources and discussions on platforms like Stack Overflow (link here), the consensus seems to lean towards utilizing stateless functions (functional components) whenever possible. Many of the life cycle methods found in ...

Accessing nodejs environment variables in a VueJS single page application

Creating a single page application with the use of Vue, running it with nodejs, and encapsulating it in a docker container poses an interesting challenge. In an attempt to adhere to the principles outlined in the 12 factor app methodology, one is advised t ...