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

Reorganizing an array of JSON data by date value with a limitation to just one

Currently, I am attempting to organize a JSON array based on the date key. However, it appears that my sorting function is either stopping after one sort or simply not functioning correctly. Here is the JavaScript code for my sorting function: function ...

Is it possible to incorporate a variable into my fetch request?

I am currently learning how to use react native and am studying some examples. Encountered a roadblock: While attempting to pass latitude in my fetch call, I encountered an error stating that "latitude" does not exist. class App extends React.Component ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...

"Unlocking the Power of mediaElementjs: Easy Steps to Accessing the Player Instance

I'm facing a small issue with the MediaElement.js player. To access the player instance, I usually use the following code (which works in HTML5 compatible browsers): // Retrieve player this.playerId = $('div#shotlist-player video').att ...

Automatically update div content using AJAX in a different approach

In my situation, I am facing a unique challenge compared to other queries. I have a div element with the following code <div id="ondiv"><?php ?></div> Within this PHP section are details of people who are currently online. Ideally, when ...

Preventing links from functioning on dynamically generated web pages

I have implemented the following code to deactivate all links on a preview page: var disableLink = function(){ return false;}; $('a').bind('click', disableLink); While this successfully disables all static links, any anchor tags loade ...

Is there a way to compare the elements of an array with those of another array containing nested arrays in order to identify matching results?

Every user in our database has specific skills assigned to them. We maintain a list of available skills with unique IDs. The objective is to filter users based on the skill we are interested in, like displaying all Janitors. We are utilizing Vue.js and im ...

"X-Requested-With" header not being included in XMLHttpRequest request

After successfully using jQuery.ajax() to make an ajax call to an MVC action, I decided to switch to using the XMLHttpRequest along with the HTML5 File API due to some forms containing file controls. However, since making this change, the MVC action no lon ...

Show a collection of elements containing attributes in JSX

I have a React component where I am displaying data from an array called pkgData: <div className="mainApp"> <div className="pkgsList"> {pkgData.map((p) => <h3 key={p.name}>{p.name}</h3> ...

Exploring the capabilities of Netlify Dev in conjunction with Vue JS and Netlify Functions for advanced development

I have a small web app that I built using Vue and Netlify functions. Everything works perfectly when deployed in production, but I encounter issues when trying to use 'netlify dev' for local development. The calls to the netlify function are fail ...

Creating intricate filters using React's map functionality

QUESTION HAS BEEN UPDATED. I am currently working on implementing a filter for my map, allowing users to specify which options they want to view using multiple selection boxes. However, I am encountering an issue with the page that appears after the user ...

An issue has occurred with the axios get request link when trying to access it through a click

When using axios in vue.js with Laravel, I am encountering an issue where the URL is incorrect in the console. Instead of http://{mylink}/messages/getMessages1, I need it to be http://{mylink}/messages/getMessages/1. The method in my file.js is as follows ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

Error: React/Express - The renderToString() function encountered an unexpected token '<'

As I work on implementing server-side rendering for my React/Express application, I have hit a snag due to a syntax error related to the use of the react-dom/server renderToString() method. In my approach, I am following a tutorial mentioned here - The sn ...

How to disable React Native yellow warnings in console using npm

Is there a way to get rid of those pesky yellow warnings flooding my npm console? It's becoming impossible to spot my own console.log messages amidst all the warning clutter. https://i.stack.imgur.com/JAMEa.jpg I've already attempted the follow ...

What are some ways to incorporate a Three.js script within a Vue project?

I encountered a challenge while trying to incorporate a three.js script written in vanilla JavaScript into a Vue project. The script utilizes the three function objLoader to import an object from a local file. While the script functions accurately in vanil ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Invoke the identical function in between two functions that make asynchronous AJAX calls

I seem to be a little lost at the moment. The code snippet below illustrates my intent, which is to use the insertChilds() function to insert child elements in the DOM in a cascading manner (or at least that's what I'm aiming for...). The challe ...