Vue-Apollo - The 'value' property is not present in the 'Readonly<Ref<Readonly<any>>>' type

MY CURRENT DILEMMA:

In my quest to seamlessly integrate vue-apollo v4 with Typescript, I have encountered a challenge.

I am in the process of retrieving data from a simple query using useQuery along with useResult.

The default return type of useResult is:

Readonly<Ref<Readonly<any>>>

SNEAK PEEK AT THE CODE:

import { GET_COUNTRY } from '../graphql/queries'
import { Country } from '../types'

setup() {
  const route = useRoute()
  const code = route.params.code

  const { result, loading } = useQuery(GET_COUNTRY, {code: code}, { 
    clientId: 'default', 
    fetchPolicy: 'cache-first'
  });
  const country = useResult(result, {}, (data) => data.country);

  console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

  return {
    country,
    loading
  }
}

INITIAL ATTEMPT:

const country: Country = useResult(result, {}, (data) => data.country);
// Type 'Readonly<Ref<Readonly<any>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

SECOND ATTEMPT:

const country = useResult(result, {}, (data) => data.country as Country);
console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

THIRD ATTEMPT:

const country: Country = useResult(result, {}, (data) => data.country as Country);
// Type 'Readonly<Ref<Readonly<Country | {}>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

FOURTH ATTEMPT:
Following insights from @tony19

const { result, loading } = useQuery<Country>(GET_COUNTRY, {code: code});
const country = useResult(result, {}, (data) => data.country);
// Property 'country' does not exist on type '{ native: string; phone: string; capital: string; currency: string...

FIFTH ATTEMPT:
After refining advice received from @tony19

// QUERY - simplified
export const GET_COUNTRY = gql`
  query getCountry($code: ID!) {
    country(code: $code) {
      code
      name
    }
  }
`
// TYPES - simplified
export interface Country {
  code: string,
  name: string
}

export type CountryQuery = {
  country: Country
}
const { result, loading } = useQuery<CountryQuery>(GET_COUNTRY, {code: code});
const country = useResult(result, {}, (data) => data.country);

A warning message pops up in vsCode:

 Property 'name' does not exist on type 'Readonly<{}>'.

ANOTHER TWIST TO THE FIFTH ATTEMPT:
In line with @tony19's guidance, making some adjustments:

type CountryQuery = {
  getCountry: Country
}

This leads to an error:

Property 'country' does not exist on type '{ getCountry: { code: string; name: string; }; }'

THE BIG QUESTION:

Can I successfully merge useResult with my custom Typescript utilities and eliminate these compatibility issues?

Answer №1

Given the following categories:

cat Type = {
  name: string
}

const GET_CATEGORY = gql`
  query GetCategory {
    getCategory {
      name
    }
  }
`

The outcome should be structured to correspond with the GET_CATEGORY query provided above:

type CategoryQuery = {
  getCategory: Type
}

Next, indicate that query category as a type parameter for useQuery():

const { result, loading } = useQuery<CategoryQuery>(GET_CATEGORY, ⋯)
                                        👆

Subsequently, the data parameter of useResult()'s function is of type CategoryQuery, therefore utilize data.getCategory.name to retrieve the category name:

                                        👇 type is CategoryQuery
const category = useResult(result, {}, (data) => data.getCategory.name);
                                                        👆

result and category are refs, thus to access the underlying information, unwrap them using .value:

console.log(category.value);
                      👆

demonstration

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

What is the method for transmitting a URL API from an ASP.NET Core server to my Angular 2 single application?

Is there a way to securely share the url of the web api, which is hosted on a different server with a different domain, from my asp net core server to my client angular2? Currently, I am storing my settings in a typescript config file within my angular2 ap ...

Altering the character by striking a key

I have a canvas with custom styling. In the center of the canvas is a single letter. Please see the code below for reference. The goal is to change the displayed letter by pressing a key on the keyboard. For instance: Letter A is centered in the canvas: P ...

Issue encountered when trying to import @tensorflow/tfjs-node in conjunction with the face-api.js library within a node.js environment

Using the @tensorflow/tfjs-node package along with face-api.js to enhance performance, here is my code snippet: // Import nodejs bindings to native tensorflow, // Not required but will significantly speed up operations (Python required) require('@tens ...

What steps are involved in setting up a point distribution system in AngularJS?

My objective is to develop a point allocation system within AngularJS. I have successfully created a basic directive that introduces DOM elements, including a span displaying "0" points and buttons for incrementing and decrementing. The total number of poi ...

What is the best way to put together the perfect attire for Threejs shaders?

I have been experimenting with using Three.js' built-in ShaderChunks for implementing lighting and fog effects, and I decided to start by mimicking a setup from one of the ShaderLib shaders. Initially, I utilized the following code snippet: customMat ...

Asserting within a specific condition's scope in TypeScript

I am facing a similar situation, type Field1Type = { a: string; } type Field2Type = { b: string; c: number; } type ObjType = { field: Field1Type | Field2Type } const field = { b: "" c: 0 } const obj = { field } as ObjType i ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

Ensure there is a sufficient gap between the top and bottom icons within the Material-UI Drawer

I'm having difficulty articulating this, but I'd like to add two different sets of icons to the Drawer component. Set 1 should be displayed at the top in a standard column format, similar to the examples provided by them. Set 2 should go at the b ...

jQuery mobile not recognizing the ID we specified

I am in the process of developing an audio application. My goal is to change the id of the Play button dynamically to "paused" when it is clicked. However, despite my efforts, clicking on the "paused" button does not pause the audio as intended. $(&ap ...

How can I trigger the offcanvas opening in Bootstrap 5 through code?

I am having an issue with a bottom offcanvas on my webpage. I want to open it when a card is clicked, but despite trying to set the necessary attributes and using code from the documentation, it only shows the backdrop briefly before immediately dismissing ...

When working with Node.JS, is it necessary to include 'event' if you include 'net' using the require statement?

As I examine the code, I notice that there is no instance of "require('event')" present. However, there is this piece of code: server.on('error', function (e) { if (e.code == 'EADDRINUSE') { console.log('Address in ...

Find non-null values inferred from a string identifier in Typescript

Imagine having a dynamic object with various keys and values, where the keys can be of any type, including null and undefined. Now, consider a function that takes an array of string paths to values within this object and returns true only if all those val ...

Guide to Conditionally Importing a Module in Angular

I am currently developing a module for Search integration. Instead of directly importing the SearchModule inside my app.module.ts file, I would like to implement a method where an API is called and the SearchModule is imported based on the API response. @N ...

Storing complex data structures in Firebase using VUEX

I am struggling to properly store my 'players' data within my team data structure. Currently, it is being saved with the team id but I need it to be nested inside of teams. Essentially, I want the players to seamlessly integrate and be appended ...

Mapping keys in a react component for efficient sorting

I'm facing some challenges when attempting to reorder keys from a state within my map function in React.. The original output is: monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...

What is the best way to retrieve a value from $http or $resource using this filter?

Within my HTML, I have a structure that looks like {{ i.userId | userName }}. Essentially, I am attempting to convert this into a name by utilizing a filter. However, I am encountering numerous challenges with the asynchronous function required to retrieve ...