Utilize useResult to access nested properties when querying GraphQL data

We have a unique approach to executing our graphql query:

// rosterDispatchGroup.query.graphql
query rosterDispatchGroup($fromDate: DateTime!) {
  rosterDispatchGroup(fromDate: $fromDate) {
    ... on ApiError {
      message
    }
    ... on RosterDispatchGroupArray {
      data {
        date
        dispatchGroup
      }
    }
  }
}

This query returns a data array or an error message in the case of an ApiError:

{
  "data": {
    "rosterDispatchGroup": {
      "data": [
        {
          "date": "2020-10-28",
          "dispatchGroup": [ "A" ]
        }
    ]
}

To integrate this data into our Vue template, we follow these steps:

import { useResult } from '@vue/apollo-composable'
import { defineComponent } from '@vue/composition-api'
import { useRosterDispatchGroupQuery } from 'src/graphql/generated/operations'

export default defineComponent({
  setup() {
    const { result, loading, error } = useRosterDispatchGroupQuery(
      () => { return { fromDate: new Date() } },
    )

    const dispatchGroups = useResult( result, [],
      (data) => data.rosterDispatchGroup.data // property data does not exist on type
    )
    return { dispatchGroups, loading, error }
  },
})

While this code functions correctly, it triggers a typescript error message:

https://i.sstatic.net/fHvn9.png

We want to ensure that we are properly handling the result using useResult without encountering any typescript errors. For reference, we utilized a tool like graphql-codegen for generating necessary TypeScript code and drew insights from a tutorial like this one.

Answer №1

Solved the issue by implementing a check for the __typename property before returning the object data 'array':

export default defineComponent({
  setup() {
    const dispatchGroups = useResult(result, [], (data) => {
      if (data.rosterDispatchGroup.__typename === 'RosterDispatchGroupArray') {
        return data.rosterDispatchGroup.data
      }
    })

    const apiError = useResult(result, null, (data) => {
      if (data.rosterDispatchGroup.__typename === 'ApiError') {
        return data.rosterDispatchGroup
      }
    })

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

Tips for creating an operation within a JSON document?

Today, I am attempting to customize the appearance of my audiobook list. However, when trying to add an aspectRatio key-value pair to each object in my JSON file, I encountered an error. https://i.stack.imgur.com/Qb3TX.png https://i.stack.imgur.com/qTkmx. ...

verify this condition prior to executing the for loop in javascript

When working with a queue in Typescript (ES6) set to run on an interval of 1 ms, it's important to consider the most efficient approach for performance. 1. setInterval(() => { //if (this._queue.filter(a => !a.running && a.cbs.length) ...

No solution was found for implementing Airbnb TypeScript in React.js (Next.js) using ESLint

screenshot I encountered an issue where I couldn't locate the Airbnb typescript option in React JS (Next JS) within ESLint. Prior to this, I had installed Storybook and mistakenly clicked "yes" when prompted to migrate ESLint to Storybook. ...

Issue Alert: Error encountered while rendering: "TypeError: route is not defined"

Greetings! Would you mind identifying the specific error for me? ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Tips for Disabling ML5 Posenet

Looking to halt Posenet after completing app task private sketch(p: any) { p.setup = () => { this.poseNet = ml5.poseNet(p.createCapture(p.VIDEO), { outputStride: 8 }); this.poseNet.on(&apos ...

Continuously encountering the error message "undefined on the instance but called during render"

I have been encountering an error consistently after binding my data components to the template. Any assistance would be greatly appreciated. code: data() { return { sireDetailsData: [], horse_show_name_prop:, } }, async created () { const ...

Is there a speedy and efficient method for rearranging a UI list?

Currently utilizing Angular 2 and Typescript. In my current project, I am displaying a basic list of JSON objects. The HTML structure is as follows: <div> <!-- List Presentation Button --> <button md-button (click)="showList( ...

What is the reason behind continuously receiving the error message stating "Not all code paths return a value here"?

Can someone help me understand why I am consistently encountering this error message from typescript? PS. I am aware that in this scenario I could simply use a boolean and not create a function, but my focus here is on typescript. I keep receiving the er ...

Different instances of the same data structure causing a global declaration error: "TS2717: Subsequent property declarations must have the same type."

Encountering an issue with version 13.2.1 of the library should while compiling with TypeScript 2.7.1 on Node 8.9.1 leads to the following error: node_modules/should/should.d.ts(237,5): error TS2717: Subsequent property declarations must have the same ty ...

Navigating with Express and Vue

Currently, I am working on a basic web page that has an index '/' and a 404 page to handle errors at '/404'. In my express app setup, I have the following configuration: // Entry Point app.use("/", express.static(resolve(__di ...

Attaching an event listener to elements with a specified Class name

Currently facing a challenge where I am trying to implement a function that captures click events on squares. The objective is to capture the click event on every button with the square class. import { Component, OnInit } from '@angular/core&apos ...

Error message: Conflicting type declarations across multiple files

I am facing a challenge with my TypeScript 'snippets' project. It seems that multiple .ts files contain type names (like Foo) that are the same. //file-a.ts type Foo = { } //file-b.ts type Foo = { } When attempting to compile, I encounter ...

Slim specific assigned parameter

Here is some code to analyze: type T = 'a' | "b" type M = { a: 1, b: 2 } function a(a: 'a') {} function m1(a: 1) {} function f<TT extends T>(t: TT, p: M[TT]) { switch (t) { case "a": { a(t) ...

What is the process for refreshing information in VueJS?

<script> export default { data() { return { data: {}, dataTemp: {} } }, methods: { updateData() { let queries = { ...this.$route.query } this.data = { ...this.data, pID: queries.pid, s ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

How can I utilize this.$apollo within a Vuex store using vue-apollo in a NUXT environment?

I am trying to save the user data from a login action in the vuex store, but I am unable to access this.$apollo. export const actions = { UPSERT_USER({ commit }, { authUser, claims }) { this.$apollo .mutate({ mutation: UPSERT_USER ...

Nuxt: Using @click event handler does not function properly with Nuxt-link component

I am currently developing a web application and I want to implement an effect that underlines the section we are currently on in the list of sections. My project is built using Nuxt. For some reason, the code snippet below is not updating the value of the ...

Kendo checkbox toggle issue with switching between true and false states is not functioning correctly

How can I make a button appear when one or more checkboxes are clicked? Currently, the toggle function only activates when I select one checkbox, and then deactivates upon selecting another. Any guidance on improving this functionality would be greatly app ...