Unable to retrieve query within async function, unable to import graphql queries externally

Is there a way to fetch characters from the parent component when a property changes and utilize these props? I attempted to use the useQuery function within a method and execute this method on prop change, but it seems like something is not functioning correctly. Additionally, I would like to make use of {result, error, loading} provided by useQuery.

The code snippet is as follows:

<script lang="ts">
import { ref, defineComponent, watch } from "vue";
import gql from "graphql-tag";
import { useQuery, useLazyQuery, useResult } from "@vue/apollo-composable";

export default defineComponent({
  props: {
    message: [String],
  },

  setup(props) {
    const pageNumber = ref<number>(1);

    const variables = ref({
      page: pageNumber.value,
      name: props.message,
    });

    const fetchCharacters = async () => {
      const { result, error, loading } = await useLazyQuery(
        gql`
          query getCharacters($page: Int!, $name: String!) {
            characters(page: $page, filter: { name: $name }) {
              info {
                count
                pages
              }
              results {
                id
                name
                image
                gender
                species
                episode {
                  episode
                }
              }
            }
            location(id: 1) {
              id
            }
            episodesByIds(ids: [1, 2]) {
              id
            }
          }
        `,
        variables
      );
      const characters = useResult(result);
      console.log(characters);
      return { characters, result, error, loading };
    };

    watch(props, (value) => {
      fetchCharacters();
      
    });

    return {};
  },
});
</script>

Any suggestions on how to achieve this successfully? Your help is greatly appreciated.

An error message I am encountering:

onServerPrefetch is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

Answer №1

1. Issue with Retrieving Query in Async Function

If you're utilizing async setup(), ensure to register lifecycle hooks prior to the initial await statement.

To resolve this, include useQuery before the async section and useResult within it.

2. Trouble with External GraphQL Query Imports

If you're using vue-cli, configure graphql-tag/loader.

module.exports = {
  chainWebpack: config => {
    config.module
      .rule('graphql').test(/\.(graphql|gql)$/).use('graphql-tag/loader').loader('graphql-tag/loader').end();
    /* ...other loader
    config.module
      .rule('svg-sprite').use('svgo-loader').loader('svgo-loader').end();*/
  },
}

Usage

import userQuery from './user.gql';
const { result } = useQuery(
  userQuery
)

or

const { result } = useQuery(
  require('./user.gql')
)

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

Remove a specific date entry from the database using VUE JS and Axios

I am encountering a challenge with Vuejs as I work on a To-Do list. The tasks need to be stored in a MySQL database, and I also want the ability to delete tasks. While I have succeeded in importing and creating data, I'm facing difficulty in deleting ...

Running a Jest test that triggers process.exit within an eternal setInterval loop with a latency of 0, all while utilizing Single

In the original project, there is a class that performs long-running tasks in separate processes on servers. These processes occasionally receive 'SIGINT' signals to stop, and I need to persist the state when this happens. To achieve this, I wrap ...

The plugin data containing 'data:application/pdf;base64,JVBERi0xLjQKJ**' was declined for loading. Content security policy cannot be configured

My approach to enforcing content security policy involves using the following code snippet: <meta charset="UTF-8" http-equiv="content-security-policy" content="object-src 'self' data:" /> However, when this i ...

Issue with const declaration in Typescript and Node.js - initializer is missing

Encountering a syntax error with the following line of code. Error message: SyntaxError: Missing initializer in const declaration const dataMap : Map<string, any> = new Map(); ...

Does installing the global npm package (@vue/cli) on Node v10.9 also automatically install Node v10.8?

This situation is quite puzzling and I have yet to find a definitive answer. It seems as though it was meant to happen this way, but it still feels odd. Here's the sequence of events: I completely removed Node from my OSX system. I then reinstalled ...

[ERROR] There was a problem encountered during the execution of the ionic-app-scripts subprocess

I encountered an error while running my Ionic project. Below is the error message: [ERROR] ionic-app-scripts has unexpectedly closed (exit code 1). The Ionic CLI will exit. Please check any output above for error details. ionic3-firebase-shopping-car ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

The navigation functionality in vue.js is experiencing issues with the router integration

As I work on securing my routers in vue.js, I have implemented user authentication to restrict access to unauthorized users. However, I encountered a loophole where a logged-in patient could access the profile of a doctor by navigating to the respective ro ...

Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have: Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" } This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular. Now, I want to populate this data into the following ...

Leveraging the `--max-http-header-size` flag with ts-node

Encountered an issue when trying to use ts-node with the --max-http-header-size 15000 flag. It works fine with regular node, but unfortunately, ts-node does not support that option ...

How to troubleshoot the issue of "Error: (SystemJS) module is not defined" in Angular 2?

I am a beginner in the world of Angular2. It is known that in Angular2, there is a way to reference a file using a relative path by defining moduleId : module.id in the component meta data. However, I have tried doing it this way and keep encountering the ...

Building a dropdown menu component in react native

Looking to implement a dropdown menu in React Native using TypeScript. Any suggestions on how to achieve this for both iOS and Android platforms? Check out this example of a dropdown menu ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

The error message says: "VueComponent.filterKategori function cannot read property 'filter' because it is undefined at line 16260 in app.js."

this is the code snippet that I'm dealing with: computed: { filterKategori() { var kategori = this.kategori.data.filter(f => { return f.induk == null && f.id_klasifikasi == this.id_klasifikasi; }); return kat ...

Efficiently capturing selections from a Dynamic Dropdown menu and storing them in a database using VueJs and Laravel

I have been working on developing a form where users can add cities based on the countries selected from a dynamic drop-down menu. While I managed to extract the category_id (foreign key) in Vue.js, I am struggling with passing it to the Laravel backend. ...

I am experiencing an issue with the PUT method on my API as it is not correctly setting the req.body data

Below is the code snippet for implementing the PUT method: [/api/[id].ts] case "PUT": try { const user = await UserModel.findOneAndUpdate( { _id: id, }, { $set: req.body, ...

Issue with page break functionality during print preview

div.pagebreak { page-break-after: always; page-break-inside: avoid; } HTML <!-- Page separator --> <div class="pagebreak" style="float: none;"><hr class="hidden-print" /></div> <app-mud-chec ...

What is the best way to organize checkboxes (either checked or unchecked) within a mat-table?

https://i.stack.imgur.com/cDQY7.png <ng-container matColumnDef="scheduled"> <th mat-header-cell mat-sort-header *matHeaderCellDef> Scheduled </th> <td mat-cell *matCellDef="let station"> ...

Using v-model with an input file is not supported

Is there a solution for not being able to use v-model in an input tag with type="file"? Here is an example of the HTML code causing this issue: <input v-model="imageReference" type="file" name="file"/> ...

What is the best way to modify the quantity property of a cart item object within the framework of this Angular 13 online shopping application?

I am currently developing an e-commerce app with a front-end built using Angular 13. The following code snippet is designed to calculate the total price of items in the shopping cart: import { Component, OnInit } from '@angular/core'; @Componen ...