When is the AbortSignal in the TanStack useQuery function considered as undefined?

The TanStack React Query documentation (visit here) provides insights on utilizing the queryFn property with an object containing a signal property for query cancellation. Check out this example:

const query = useQuery({
  queryKey: ['todos'],
  queryFn: async ({ signal }) => {
    const todosResponse = await fetch('/todos', {
      signal,
    })
    const todos = await todosResponse.json()
    const todoDetails = todos.map(async ({ details }) => {
      const response = await fetch(details, {
        signal,
      })
      return response.json()
    })

    return Promise.all(todoDetails)
  },
})

A challenge arises when using TypeScript as the type for the signal property is defined as AbortSignal | undefined. This conditionally checking if the signal is set can complicate the code significantly. It would be helpful to understand the circumstances under which this signal object is not defined. Any suggestions or insights on this matter would be greatly appreciated.

Answer №1

react-query v4.29.11

When the AbortController class exists, the signal will be present. Let's dive into the source code:

The signal property is added to the query function context using the addSignalProperty() function, as shown below:

    const addSignalProperty = (object: unknown) => {
      Object.defineProperty(object, 'signal', {
        enumerable: true,
        get: () => {
          if (abortController) {
            this.abortSignalConsumed = true
            return abortController.signal
          }
          return undefined
        },
      })
    }

    addSignalProperty(queryFnContext)

The abortController can be acquired through the getAbortController() function.

export function getAbortController(): AbortController | undefined {
  if (typeof AbortController === 'function') {
    return new AbortController()
  }
  return
}

Hence, the TS type of the signal property is: AbortSignal | undefined.

This is also mentioned in the official documentation.

If the runtime environment does not support the AbortController API, the query function will receive undefined. You have the option to polyfill the AbortController API with available alternatives.

Answer №2

So, I encountered a similar situation and found a solution that worked for me.

async function fetchUserData({
    queryKey,
    signal,
  }: QueryFunctionContext<[string, Person]>): Promise<User> => {
    const [, selectedUser] = queryKey;
    const response = await axios.get(`/api/person?person=${selectedUser}`, {
      signal,
    });
    return response.data;
  };

  const { data, error, isLoading } = useQuery({
    queryKey: ["users", selectedUser as Person],
    queryFn: fetchUserData,
    enabled: !!selectedUser,
  });

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 best way to fetch the data from this API?

function fetchCoinPrice(coinName) { return axios .get( `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coinName}&tsyms=EUR` ).then((response) => (response.data[coinName]["EUR"])); The JSON response for the coin "BTC" is: ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

The type "AppRouterInstance" cannot be assigned to type "nextRouter"

Within my Next.js project, a registration form is included as seen below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form" ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

The 'data' property is absent in the 'never[]' type, whereas it is necessary in the type of product data

Hello, I am new to TypeScript and I'm struggling with fixing this error message: Property 'data' is missing in type 'never[]' but required in type '{ data: { products: []; }; }'. Here is my code snippet: let medias :[] ...

Error: The Turborepo package restricts the use of import statements outside of modules

I created a typescript "test" package in turborepo, which imports and exports typescript functions. Due to being in turborepo, it gets copied to node_modules/test. When attempting to run import {func} from "test", an error is thrown: SyntaxError: Cannot ...

The Cypress-TinyMCE package consistently returns undefined for the editor instance when using TypeScript

My current project involves building a React JS application with TypeScript, where I utilize the TinyMCE editor within a form. To further enhance my development process, I am incorporating integration tests using Cypress in TypeScript. However, I have enco ...

Incorporate FontAwesome global components into your Vue project using TypeScript

Hey there, I'm a TypeScript newbie and looking to incorporate FontAwesome icons into my Vue 3 App. Here's the setup: Here is my main.ts : import Vue, { createApp } from 'vue'; import './registerServiceWorker'; import { librar ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

I'm having trouble inputting text into my applications using React.js and TypeScript

I am encountering an issue where I am unable to enter text in the input fields even though my code seems correct. Can anyone help me figure out what might be causing this problem? Below is the code snippet that I am referring to: const Login: SFC<LoginP ...

Unable to impose a restriction on the number input field limit

My input field has a type of "number" with the min and max attributes applied to limit user input. However, I am facing an issue where users can still enter values beyond the set limit. How can I prevent users from entering values above the specified lim ...

Utilizing an Angular component for multiple purposes

For my Angular app, which is component-based and uses Angular version 1.5.5 with TypeScript, I have a header component that includes a country dropdown. This header component is used across multiple pages. However, when a country is selected from the dropd ...

Having trouble implementing the Material UI time picker because it does not meet the required DateTime format

REVISE I recently switched my dataType from DateTime to TimeSpan in my code. I have a functioning MVC version that already uses TimeSpan, and the times are posted in HH:MM format. Now, I am unsure if the issue lies with the headers set up on Axios or if it ...

A guide on implementing getStaticProps using TypeScript in Next.js

Why am I consistently receiving undefined results when attempting to retrieve all posts from my backend? What could be causing this issue? import { AppContext } from '@/helpers/Helpers' import axios from 'axios' import { GetStaticProps} ...

Challenges encountered when implementing a personal library in a separate project

After updating a library I own, I seem to have encountered an issue when trying to use it in another project. However, the reason for this problem eludes me. A multitude of error logs with a similar theme are appearing: ERROR in ./node_modules/@company-na ...

Angular firing off select option with object properties

Within my Angular application, I am faced with a situation involving a <select> element that contains a list of <option> elements whose values are associated with objects. My goal is to capture the last selected value using the following code: ...

I am encountering unexpected behavior with NextJS's getInitialProps function, as it is giving me a compiler error stating "varName not found on type {}"

I seem to be stuck on a simple syntax issue while working with NextJs. I am attempting to perform dynamic server-side fetches using the getInitialProps pattern. However, the compiler is unable to recognize the return of getInitialProps in the regular func ...

Looking for a shortcut in VSCode to quickly insert imports into existing import statements or easily add imports as needed on the go?

It seems that the current extensions available on the VSCode marketplace struggle to properly add Angular imports. For example, when I try to import OnInit using the Path IntelliSense extension: export class AppComponent implements OnInit It ends up impo ...

Angular: Issue with object instantiation - Unable to assign property

Having trouble populating my array due to instantiation issues. Defined Models: user: User = { firstName: "", lastName: "", address: "" } order: Order = { OrderId: "", User: this.user, TotalPrice: 0, OrderItems: [] } Attempting to populat ...

Ways to troubleshoot and resolve the npx create-next-app issue

Every time I try to create a new app using npx create-next-app@latest --typescript, it keeps giving me this error message: npm ERR! code ENETUNREACH npm ERR! syscall connect npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/create-n ...