react-query: The 'isSuccess' property types do not match

i have the following code snippet:

import { get } from "lodash-es"
import {useQuery} from '@tanstack/react-query'

type QueryResult<TData extends object> =
    | {
          isSuccess: false
          isPending: true
          isError: false
          data: undefined
      }
    | {
          isSuccess: true
          isPending: false
          isError: false
          data: TData
      }

class DataListManager<TData extends object, TPath extends keyof TData> {
    constructor(
        private readonly _query: QueryResult<TData>,
        private readonly _path: TPath,
    ) {}

    get query() {
        const items = get(this._query.data, this._path) ?? []

        return {
            ...this._query,
            data: {
                items,
            },
        }
    }
}

type Transaction = {}

function useTransactionsListManager() {
    const query = useQuery({
        async queryFn() {
            const data = await new Promise<{transactions: Array<Transaction>}>(resolve => {
                resolve({
                    transactions: []
                })
            })

            return data
        },
        queryKey: ['transactions']
    })

    //  Argument of type 'UseQueryResult<{ transactions: Transaction[]; }, Error>' is not assignable to parameter of type 'QueryResult<{ transactions: Transaction[]; }>'.
    //   Type 'QueryObserverRefetchErrorResult<{ transactions: Transaction[]; }, Error>' is not assignable to type 'QueryResult<{ transactions: Transaction[]; }>'.
    //     Type 'QueryObserverRefetchErrorResult<{ transactions: Transaction[]; }, Error>' is not assignable to type '{ isSuccess: true; isPending: false; isError: false; data: { transactions: Transaction[]; }; }'.
    //       Types of property 'isSuccess' are incompatible.
    //         Type 'false' is not assignable to type 'true'.ts(2345)
    return new DataListManager(query, "transactions")
}

Why am I getting this error and how can I resolve it?

Update

I am unable to utilize UseQueryResult inside DataListManager due to architectural limitations.

Playground

Answer №1

There is no need to create your own QueryResult type; you can simply import it from @tanstack/react-query

import {useQuery, UseQueryResult} from '@tanstack/react-query'

class DataListManager<TData extends object, TPath extends keyof TData> {
    constructor(
        private readonly _query: UseQueryResult<TData>,
        private readonly _path: TPath,
    ) {}

    get query() {
        const items = get(this._query.data, this._path) ?? []

        return {
            ...this._query,
            data: {
                items,
            },
        }
    }
}

If you want to customize it further, you can use Pick

type QueryResult<TData extends object> = Pick<UseQueryResult<TData>, "isSuccess" | "isPending" | "isError" | "data">

Interactive Demo

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

Splitting Ngrx actions for individual items into multiple actions

I'm currently attempting to create an Ngrx effect that can retrieve posts from several users instead of just one. I have successfully implemented an effect that loads posts from a single user, and now I want to split the LoadUsersPosts effect into ind ...

What is the method for installing TypeScript declarations for packages with scopes or namespaces using @types?

My current challenge involves the use of TypeScript and my desire to utilize a scoped package such as @foo/bar or @babel/core that does not include its own type declarations. My attempted solution so far has been to execute the following command: npm ins ...

Is it possible to assign an alternative name for the 'require' function in JavaScript?

To ensure our node module is executable and includes dependencies for requiring modules at runtime, we utilize the following syntax: const cust_namespace = <bin>_require('custom-namespace'); This allows our runtime environment to internal ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

Guide to effortlessly loading files with designated decorators in a node.js application

Within the realm of Project A, I have constructed a decorator and am seeking a method to automatically load all these decorators upon initializing the application in Project B, which is the project utilizing Project A. Is there a way to accomplish this tas ...

How can we set up the Typescript Compiler to recognize typings and modules effectively?

I have been working on a TypeScript project with the following structure: <work folder>/Scripts/ (project root) +-- App +--- subfolder1 +--- subfolder2 +-- typings After openi ...

What determines the narrowing of a type when it is defined as a literal versus when it is returned from a function?

I'm really trying to wrap my head around why type narrowing isn't working in this scenario. Here's an example where name is successfully narrowed down: function getPath(name: string | null): "continue" | "halt" { if (n ...

What's the reason behind the usage of `declare` being allowed in class properties, but not in methods

class A { // specified explicitly for properties only declare foo(): string; // allowed for a property but not a method declaration declare bar: string; } What is the reasoning behind this specific restriction? Can someone provide an expla ...

The breakpoint was overlooked due to the absence of generated code for TypeScript on a Windows operating system

Currently, I am in the process of debugging a TypeScript project. The structure of the project folder and tsconfig.json file is illustrated below: https://i.sstatic.net/epIEC.jpg Furthermore, my launch.json file is displayed below: https://i.sstatic.net ...

Extensive Testing Suite Incorporating `fit` and Triggering Jasmine Timeout

My test suite is quite extensive, with over 250 tests and more yet to be added. I am encountering an issue with the fit function where it passes the end of the test, then continues "running through" while skipping the remaining tests, resulting in a length ...

Error message: Unable to set the uploaded file in the specified state within a React application

I am currently working on a react application that involves file uploads. My goal is to update the state variable with the uploaded file in either .docx or .pdf format as soon as it is uploaded. However, when I try to set the state, it shows up as undefine ...

Saving the contents of a book in an Ionic mobile application

I'm working on an app that features an e-reader function for users to read a single book. Where should I save the text data for the book? I experimented with storing pages as .json files in the assets folder but ran into issues. The path to the asset ...

Discovering the IP address of Azure Functions

Is there a way to retrieve the IP address of an Azure function? I am looking for a method to make a request to the function and receive its IP address in return. I attempted the following code, but it hung indefinitely without generating any results: imp ...

Navigating the proper utilization of exports and subpaths in package.json with TypeScript

As a newbie in creating npm packages using TypeScript, I've encountered some issues that I believe stem from misinterpreting the documentation. Currently, I am working with Node 16.16.0 and npm 8.13.2. Here is the structure of my project: src/ ├─ ...

In TypeScript with React, utilizing ref to access the video element and trigger the .play() method

I have a TypeScript React video component that I want to play when clicked. My approach is to use a click handler that accesses the video through a ref and calls .play(), but I keep encountering this error: TS2339: Property 'play' does not exist ...

The feature of getDisplayMedia is not included in TypeScript 3.8

I am currently developing a .Net Core/Angular 8 application in Visual Studio. Within the Angular (ClientApp) section of my project, I have TypeScript 3.5.3 located in node_modules, which includes the following definition in lib.dom.d.ts: interface Navigat ...

Is there a way for me to retrieve the callback parameters?

Can the parameters of the callback function be accessed within the 'outer' function? function f(callback: (par1: string)=>void): void { // Is it possible to access 'par1' here? } ...

How can we exclude fields from JSON.stringify in type-graphql entities?

Utilizing https://github.com/MichalLytek/type-graphql for crafting our graphql schema has posed a challenge. When we serialize the TypeScript entity object, it does not adhere to the field annotations in our GQL entities, resulting in unwanted data leakage ...

Turn off the ability to select months in PrimeNG Calendar using Typescript

In my Angular 7 project, I am utilizing PrimeNG Calendar and I am looking to disable the month navigator at the component level based on certain conditions. For example, if the current month is February, I want to disable the month navigator after March. ...