TRPC error: The property 'useInfiniteQuery' is not found in the type '{ useQuery'

Issue with TRPC

I am facing a problem with my tweetRouter that has a timeline query returning tweets and a NextCursor. However, I encounter an error when trying to access useInfiniteQuery in my components.

** Property 'useInfiniteQuery' does not exist on type '{ useQuery: **

Translation: Trying to access useInfiniteQuery on an object where it doesn't exist.

Here is the component causing trouble:

export function Timeline() {
  const data = trpc.tweet.timeline.useInfiniteQuery(
    {
      limit: 10,
    },
    {
      getNextPageParam: (lastPage) => lastPage.nextCursor,
    }
  );

  return (
    <Container maxW="xl">
      <CreateTweet />
      <Box
        borderX="1px"
        borderTop="1px"
        borderColor={useColorModeValue("gray.200", "gray.700")}
      >
        {data?.tweets.map((tweet) => {
          return <Tweet key={tweet.id} tweet={tweet} />;
        })}
      </Box>
    </Container>
  );
}

This is my tweet.ts router:

import { z } from "zod";
import { tweetSchema } from "../../../components/CreateTweet";
import { protectedProcedure, publicProcedure, router } from "../trpc";

export const tweetRouter = router({
  create: protectedProcedure.input(tweetSchema).mutation(({ ctx, input }) => {
    const { prisma, session } = ctx
    const { text } = input

    const userId = session.user.id

    return prisma.tweet.create({
      data: {
        text,
        author: {
          connect: {
            id: userId,
          }
        }
      }
    })
  }),
  timeline: publicProcedure.input(
    z.object({
      cursor: z.string().nullish(),
      limit: z.number().min(1).max(100).default(10)
    })
  ).query(async ({ ctx, input }) => {
    // The implementation code for timeline query goes here
  })
})

This is my Prisma model structure:

model Tweet {
  id   String @id @default(cuid())
  text String

  author   User   @relation(fields: [authorId], references: [id])
  authorId String

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

The auto-complete feature only shows useQuery and useSuspenseQuery.

I was expecting to implement infinite scroll functionality using useInfiniteQuery.

Answer №1

Changing the zod input validation property from cursorId to cursor was necessary.

I also successfully tested your timeline publicProcedure after installing a fresh t3-app.

 getAll: publicProcedure
    .input(
      z.object({
        take: z.number().int(),
     // cursorId: z.string().nullish(),
        cursor: z.string().nullish(),
      }),
    ).query...

Answer №2

To resolve the issue, I suggest updating your tsconfig.json file by setting compilerOptions.strict to true. This solution worked for me.

Answer №3

Encountered the same issue using Next.js 13.4.1, TRPC 10.25.1, and Tanstack Query 4.29.5.

The TRPC documentation for useInfiniteQuery mentions:

"Your procedure needs to accept a cursor input of any type (string, number, etc) to expose this hook."

This dynamic modification of the type isn't functioning as expected.

Adding

"compilerOptions": { "strict": true }
in your tsconfig.json does resolve the issue, but it comes with additional complexities that I preferred not to introduce in my codebase.

The workaround I discovered was to redefine the type of the TRPC procedure as 'any', like so:

const timelineProcedure: any = trpc.tweet.timeline;
const data = timelineProcedure.useInfiniteQuery(
  {
    limit: 10,
  },
  {
    getNextPageParam: (lastPage) => lastPage.nextCursor,
  }
);

Answer №4

I'm sorry to inform you that the root router configuration was not shared in _app.ts file

It should be structured like this:

export const appRouter = router({
  tweet: tweetRouter,
});

export type AppRouter = typeof appRouter;

If you adhere to this convention, there shouldn't be any issues. If you need further assistance, I am more than willing to help. I have experience working with useInfiniteQuery() and encountered no problems.

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

React component state remains static despite user input

I am currently in the process of developing a basic login/signup form using React, Typescript (which is new to me), and AntDesign. Below is the code for my component: import React, { Component } from 'react' import { Typography, Form, Input, But ...

The process of exporting a singleton instance

I have created a new class called AppViewModel with a setting property set to 1: class AppViewModel { setting: number = 1; } export = AppViewModel; Afterward, I imported the class and instantiated it within another class named OrderEntry: import AppV ...

Tips for customizing the legend color in Angular-chart.js

In the angular-chart.js documentation, there is a pie/polar chart example with a colored legend in the very last section. While this seems like the solution I need, I encountered an issue: My frontend code mirrors the code from the documentation: <can ...

Exploring Angular 2: Incorporating multiple HTML pages into a single component

I am currently learning Angular 2 and have a component called Register. Within this single component, I have five different HTML pages. Is it possible to have multiple templates per component in order to navigate between these pages? How can I implement ro ...

What is the best way to sift through slug data?

Struggling to display related posts from the same category in my project using Sanity for slug data. Attempted fetching all data and storing it in the state but unsure how to filter based on the current post's category. I'm thinking about leverag ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

When examining two arrays for similarities

I am dealing with two arrays within my component arr1 = ["one", "two"] arr2 = ["one", "two"] Within my HTML, I am utilizing ngIf in the following manner *ngIf="!isEnabled && arr1 != arr2" The isEnabled condition functions as expected, however ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

What about combining a fat arrow function with a nested decorator?

Trying to implement a fat arrow function with a nestjs decorator in a controller. Can it be done in the following way : @Controller() export class AppController { @Get() findAll = (): string => 'This is coming from a fat arrow !'; } Wh ...

Exploring the power of NestJS integration with Mongoose and GridFS

I am exploring the functionality of using mongoose with NestJs. Currently, I am leveraging the package @nestjs/mongoose as outlined in the informative documentation. So far, it has been functioning properly when working with standard models. However, my p ...

What purpose does a private property serve within the interface?

Given the following code snippet: class X { bar() { return "bar" } constructor(private readonly x: number){} } interface Y extends X { } const f = (y: Y) => { console.log(y.bar()); } f({ bar: () => "tavern"}); The code does ...

"Optimizing Performance: Discovering Effective Data Caching

As a developer, I have created two functions - one called Get to fetch data by id from the database and cache it, and another called POST to update data in the database. However, I am facing an issue where I need to cache after both the get and update oper ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

AngularJS and TypeScript encountered an error when trying to create a module because of a service issue

I offer a service: module app { export interface IOtherService { doAnotherThing(): string; } export class OtherService implements IOtherService { doAnotherThing() { return "hello."; }; } angular.mo ...

Exploring the world of unit testing in aws-cdk using TypeScript

Being a newcomer to aws-cdk, I have recently put together a stack consisting of a kinesis firehose, elastic search, lambda, S3 bucket, and various roles as needed. Now, my next step is to test my code locally. While I found some sample codes, they did not ...

Leveraging IF conditions on part of the worksheet title

Currently, my script is performing the task of hiding three columns for tabs in a workbook that start with "TRI". However, the execution speed is quite sluggish. I am seeking suggestions on how to optimize and enhance the performance. If possible, please p ...

What are the steps to resolve TypeScript errors in OpenLayers version 6.6.1?

Since updating to OpenLayers 6.6.1, I have been bombarded with numerous typescript errors related to generics. For example... import olLayerVector from 'ol/layer/Vector'; import olFeature from 'ol/Feature'; public static highlightOver ...

When using expressjs and typescript, you may encounter an error stating that the type 'typeof <express.Router>' cannot be assigned to the parameter type 'RequestHandlerParams'

Working on my project using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped. I've set up a router and want to access it from a subpath as per the official 4.x documentat ...

What is the process for importing a map from an external JSON file?

I have a JSON file with the following configuration data: { "config1": { //this is like a map "a": [ "string1", "string2"], "b": [ "string1", "string2"] } } Previously, before transitioning to TypeScript, the code below worked: import ...

Personalizing the appearance controls of A-frame with a unique TypeScript-written custom component?

Currently, I am in the process of developing custom look controls for A-Frame based on their official documentation. This custom component is being written in TypeScript as part of an Angular project that enforces tslint rules restricting the use of this o ...