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

Tips on clearing and updating the Edit Modal dialog popup form with fresh data

This code snippet represents my Edit button functionality. The issue I am facing is that I cannot populate my Form with the correct data from another component. Even when I click the (Edit) button, it retrieves different data but fails to update my form, ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

Concealing a VueJs component on specific pages

How can I hide certain components (AppBar & NavigationDrawer) on specific routes in my App.vue, such as /login? I tried including the following code in my NavigationDrawer.vue file, but it disables the component on all routes: <v-navigation-drawer ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...

Establishing the initial state in React

Can someone help me with setting the default state in React? I'm working on a project that allows files to be dropped onto a div using TypeScript and React. I want to store these files in the state but I'm struggling with initializing the default ...

What could be causing these Typescript compilation errors I am experiencing?

I am puzzled by the appearance of these errors, especially since I copied the entire ClientApp folder from a running application where they did not exist. https://i.sstatic.net/tcO5S.png Here is the structure of my project: https://i.sstatic.net/P4Ntm.p ...

Issue arises when trying to set object members using a callback function in Typescript

I am facing a peculiar issue that I have yet to unravel. My goal is to display a textbox component in Angular 2, where you can input a message, specify a button label, and define a callback function that will be triggered upon button click. Below is the c ...

How can I turn off automatic ellipsis on my IOS device?

Currently, I am working on a web application that involves displaying location descriptions retrieved from an API. The issue I am encountering is that the description is being cut off with an ellipsis after a certain number of lines when viewed on an iPhon ...

Every time you try to import a config.json file in Typescript, it never fails

I have the most recent version of Visual Studio Code installed. Visual Studio Code is currently utilizing TypeScript v3.3.3. I've successfully installed the following packages via npm, both locally (save-dev) and globally: TestCafe v1.1.0 Core-JS v ...

Creating a redux store with an object using typescript: A step-by-step guide

Having recently started using Redux and Typescript, I'm encountering an error where the store is refusing to accept the reducer when working with objects. let store = createStore(counter); //error on counter Could this be due to an incorrect type set ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

`How can TypeScript scripts be incorporated with Electron?`

As I work on my simple electron app, I am facing an issue where I need to include a script using the following code: <script src="build/script.js"></script> In my project, I have a script.ts file that compiles to the build folder. im ...

`Is it possible to integrate npm libraries with typescript and ES6?`

I am looking to focus on using ES6 as the output for a node server-side app that I plan to run on the cutting-edge iojs distribution, which hopefully has support for the latest ES6 syntax. However, I'm unsure about how to integrate standard NPM libra ...

Function Type Mapping

I am in the process of creating a function type that is based on an existing utility type defining a mapping between keys and types: type TypeMap = { a: A; b: B; } The goal is to construct a multi-signature function type where the key is used as a ...

Tips for activating automatic building of packages when utilizing pnpm install?

Our unique project is utilizing a combination of pnpm, workspace, and typescript in adherence to the monorepo standard. Upon cloning the repository, we execute a pnpm install command to download dependencies and establish links between local packages. De ...

Tips on effectively utilizing Chart.js with Typescript to avoid encountering any assignable errors

I'm encountering an issue while utilizing the Chart.js library in my Angular application with Typescript. The error message I'm receiving is as follows: Error: Object literal may only specify known properties, and 'stepSize' does not e ...

Error in TypeScript detected for an undefined value that was previously verified

I have developed a function that can add an item to an array or update an item at a specific index if provided. Utilizing TypeScript, I have encountered a peculiar behavior that is puzzling me. Here is the Playground Link. This simple TypeScript functio ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...

What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects. Within the root directory, there is a folder called /declarations, containing several ...