The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Property 'isLoading' was accessed during render but is not defined on the instance." Any help or advice on how to resolve this issue would be greatly appreciated!

Dependencies:

"vue": "^3.2.12", "vue-query": "^1.11.0"

Todo.vue


import {onMounted} from 'vue';

export default {
  setup() {
    const fetcher = async () => {
      await fetch('https://jsonplaceholder.typicode.com/todos').then(response =>
        response.json()
      );
    };

    onMounted(() => {
      const {data, isError, error, isLoading} = useQuery('todos', fetcher);
      console.log(data);
      return {isLoading, isError, data, error};
    });
  }
};

App.vue


<script>
import {defineComponent} from 'vue';
import {useQueryProvider} from 'vue-query';
import {VueQueryDevTools} from 'vue-query/devtools';

export default defineComponent({
  components: {VueQueryDevTools},
  name: 'App',
  setup() {
    useQueryProvider();
  }
});
</script>

<template>
  <VueQueryDevTools :initialIsOpen="true" />
  <router-view />
</template>

main.js


import {createApp} from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

import './index.scss';

createApp(App)
  .use(store)
  .use(router)
  .mount('#app');

Answer №1

If you want to ensure your component works properly, a small adjustment is needed.

const fetcher = async () => {
    await fetch('https://jsonplaceholder.typicode.com/todos').then(response =>
      response.json()
    );
  };

export default {
  setup() {
    const {data, isError, error, isLoading} = useQuery('todos', fetcher);
    console.log(data.value);
    return {isLoading, isError, data, error};
  }
};

All values returned by vue-query are reactive references, so make sure to access them with .value. This reactivity feature is crucial for automatic updates on the values.

Additionally, remember to include your useQuery calls directly in the setup function. They will execute and update as needed without any manual intervention.

To see a functional example of this in action, check out the link: https://github.com/DamianOsipiuk/vue-query/tree/main/examples/simple

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

Angular decode UTF8 characters with pascalprecht.translate

I'm facing issues with UTF8 characters when using SanitizeValueStrategy('sanitize'). This is necessary because the client will be editing texts in language files and may include tags like <b> or <i>... I want to rely exclusively ...

A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations. For example, when removing properties from objects, I usually use the following function: function cloneOmit ...

Mapping geographic coordinates with a null projection using D3

With d3.geo.path having a null projection due to TopoJSON already being projected, it can be displayed without any additional transformation. My goal is to plot data in the format of [longitude, latitude] on a map. Here is a simplified version of my code: ...

Looking for a resolution with NicEditor - Seeking advice on incorporating custom select options

I recently started using NICInline Editor and found a helpful sample at Is there a way to incorporate custom options into this editor? I would like the selected option's value to be inserted right at the cursor point of the Editor Instance. Query: H ...

Troubleshooting problems with AngularJS placeholders on Internet Explorer 9

On my partial page, I've included a placeholder like this: <input name="name" type="text" placeholder="Enter name" ng-class="{'error':form.name.$invalid}" ng-model="Name" required /> I have also set up client side validation for the ...

Using XMLHttpRequest with gzip compression

Utilizing the request module in node.js makes it simple to create a request that can retrieve and correctly decompress compressed data from the source: var request = require('request'); var requestOptions = { url: 'http://whatever.com/g ...

Combining the devexpress dxDataGrid with Angular's $scope for seamless web development

I'm encountering difficulties with binding $scope in angular and dxDataGrid. Utilizing the devexpress library dx.all.js, which enhances the dxDataGrid with various features, I have a div for dx-data-grid and attempting to transfer the selected row da ...

Encounter issue when using GAS withSuccessHandler function

I've developed a Google Sheets add-on that utilizes a modal dialog for the user interface. I encountered an issue with the success handler not running as expected, so I created a basic test interface to troubleshoot the problem. After the server-side ...

Utilizing Ember to transmit models to Bootstrap Popovers

Seeking assistance from anyone familiar with utilizing Bootstrap for Ember components to help resolve an issue. I am trying to understand how to pass a model to the component when using {{bs-bind-popover}} <div {{bs-bind-popover templPop}}>Show pop ...

Is it possible to integrate a JavaScript library into the Vue prototype?

I've recently integrated ProgressBar.js library into my app, which is built using vue and laravel with laravel mix. After installing ProgressBar.js via npm install, I am unsure how to incorporate it into my .vue files. I'm considering adding it t ...

How can I use querySelector in JavaScript to target all div elements that have the same class?

I'm having an issue with the document.querySelector in my JavaScript code. It currently only selects the first div that contains the class "test", but I need it to select all such divs. Is there a way to achieve this using my existing JavaScript? ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...

Inserting multiple rows in MySql using JavaScript through a URL pathUnique: "

Hello there! I am currently attempting to send an array of objects to my MySql Database via an API endpoint. Below is the code snippet from my API: app.get("/orderdetails/add", (req, res) => { const { item__, Qty_Ordered, Unit_Price, ...

How can you effectively transfer arguments from one component to another using router.push() in Vue.js?

I need help with implementing a feature where upon clicking the edit button in a row, all the details from that particular row should be passed to a form component. I want to populate the form fields with default values from the parameters provided. Can ...

While making a promise, an error occurred: TypeError - Unable to access the property '0' of null

I encountered an issue when trying to assign data from a function. The error appears in the console ((in promise) TypeError: Cannot read property '0'), but the data still shows on my application. Here is the code: <template> ...

How to change the focus on a Material UI input field

I am facing an issue with resetting/clearing an input field using a button click: Take a look at the code here for reference. const searchInput = useRef(null); const clearInput = () => { searchInput.current.value = ''; searchInput ...

The Echart bar graph is not displaying when trying to use JSON data

Seeking assistance as a beginner in building Basic Bar inverted axes using json data. I am trying to achieve a chart similar to Bar Inverted Axes, but encountering issues with the chart not displaying properly. Utilizing Angular to develop the web applicat ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

"Troubleshooting issue: Popup in react-leaflet fails to display upon clicking

Currently, I have integrated react-leaflet into my ReactJS application to dynamically create markers with popups. However, when implementing the code as shown below, the popup box fails to display and an error message appears in the web developer console. ...

Concealing URL parameters in ui-sref (using ui.router)

Here is the HTML code I am working with: <a ui-sref="videoParent.Display.video({videoName:'[[sVid.slug]]', videoId:'[[sVid.videoID]]'})"><p>[[sVid.name]]</p></a> The parameters videoName and videoId are retriev ...