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

"Strategies for effectively utilizing the .find method to locate specific users within a database

I'm currently working on developing a User Authentication system, but I've hit a roadblock when it comes to verifying users. Specifically, I'm struggling with understanding how to iterate through all of my users in order to filter out their ...

Distinguish between datalist selection and text input in BootstrapVue Autocomplete

When looking at the code snippet provided below, I'm trying to figure out the appropriate event/method to determine whether the value entered in the input field was manually typed or selected from the <datalist>. SAMPLE CODE: <div> &l ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...

Utilizing HTML documents instead of images in Owl Carousel 2

I am currently utilizing owl carousel 2 to construct a basic sliding carousel. However, I am only using images at the moment and would like to incorporate HTML files instead. These HTML files contain multiple divs where images can be inserted, and instead ...

NPM: Handling multiple prehooks with the same name

Is it possible to have multiple prehooks with the same name in my package.json file? For example, having two instances of pretest: "scripts": { "start": "react-scripts start", ... "pretest": "eslin ...

Guide to authenticating users using Vue JS and Django

Currently, I am collaborating on a compact university venture utilizing Vue JS, Django2, and Django Rest Framework. The project involves two distinct user roles with varying actions within the application. The aspect that is leaving me puzzled is the logi ...

Select an image based on the input value provided

I'm new to coding and I'm attempting to replicate the search functionality of icomoon where typing a word displays related images. However, I'm facing an issue where I can't seem to get the value entered in the input field to trigger an ...

Is it possible to exclude a certain prop from a styled component that has emotions?

Within my code, there exists a component called BoxWithAs, which is defined as follows: const BoxWithAs = styled.div( { WebkitFontSmoothing: 'antialiased', MozOsxFontSmoothing: 'grayscale' // And more … } ); Everythin ...

Creating Personalized Checkboxes for Internet Explorer Versions 7 and 8

I am currently in the process of implementing custom checkboxes for my website. Everything is functioning smoothly on browsers such as IE9 and other modern ones. However, I am encountering issues with IE8 and 7. Below is a snippet of my CSS code: input[typ ...

Troubleshooting Problems with Google Maps and Javascript/JSON in Internet Explorer

Currently, I am utilizing the Google Maps API to construct a map that displays store locations in close proximity to a user-specified location. Everything is functioning properly, however, I am encountering an error in Internet Explorer that I would like t ...

`Loading CSS files in Node.js with Express``

My CSS isn't loading properly when I run my HTML file. Even though the HTML is correctly linked to the CSS, it seems like express and node.js are not recognizing it. I find it confusing to understand the articles, tutorials, and stack overflow questio ...

Tips for implementing server-side rendering in Jade using an Array of JSON objects instead of just a single JSON object

In my Node.js server, I am working with an array of JavaScript objects retrieved from a MySQL query. To pass this array to my Jade template, I use the following code in my router.js: data = JSON.stringify(rows[0]); res.render('yourUploads', {fro ...

Crafting an interactive saturation effect for mouseover interactions in a circular design

I'm looking to create a unique hover effect for my images. I have both a desaturated version and a full color version of the same image. My idea is to have mousing over the desaturated image reveal a circle spotlighting the color version underneath, a ...

Import the complete JSON file into a variable as an array

I am struggling with loading an external json file (locations.json) into a variable and then using the information found here: http://www.json.org/js.html Despite trying various methods, I have not been successful in populating the variable. Even after fo ...

Display and conceal button while scrolling in both directions

Seeking assistance with solving a coding challenge. I have created a function that reveals a button (an arrow pointing from bottom to top) when scrolling down. Now, I aim to implement another feature where the button appears after scrolling over 500 pixe ...

Can a Javascript file be concealed from view?

Imagine a scenario where the localhost root file is served an HTML file using the following code: app.get('/', (req, res) => res.sendfile('index.html')) Is it possible to include JavaScript files in the HTML document that are not a ...

Is it possible to utilize AngularJS' ng-view and routing alongside jade?

Currently, I am diving into the world of the MEAN stack. I noticed that Express utilizes jade by default, but I decided to experiment with it even though I can easily use html instead. When attempting to route with Angular, like so: ... body div(ng-view ...

Issue with character encoding in jQuery-ui tabs

Special characters in Swedish are replaced when configuring the tabTemplate option. For instance, using "ΓΆ" in the href attribute: var $tabs = $("#tabs").tabs('option', 'tabTemplate', '<li><a href="#ΓΆ">#{label}</ ...

Confirm that the method has been called by utilizing the AVA testing framework

As I work on creating a unit test for my React component using tools like Ava and Enzyme, I encounter an issue. My goal is to create a simple unit test that checks if a certain method has been called. The test should pass if the method has indeed been call ...

Tips for choosing elements in JavaScript using querySelector even after they've been included in the code using innerHTML

Within the scenario below, a parent element is present in the HTML code and the span element with a class of 'child' is nested within the parent element using the createChild function. Subsequently, the content of the child element is modified el ...