How should trpc query calls be implemented in a Next.js application for optimal performance?

Transitioning from pure frontend React to Next.js, I am currently working on implementing trpc calls to the backend. While this is a familiar process for me, it seems that the approach I've been using may not be appropriate in this case.

const [weight, setWeight] = useState<ChildWeightDataType[]>([]);

useEffect(() => {
  if (activeChildId) {
    const clientQuery =  trpc.children.getWeight.useQuery({
      childId: activeChildId
    });
    setWeight(clientQuery.data)
  }
}, [activeChildId]);

It appears that the main issue lies in the fact that useQuery is a hook, and using it within another hook is not allowed. What would be the correct pattern to follow in this scenario?

Answer №1

Utilize the useQuery method and extract the data attribute by deconstructing it.

const {data} = trpc.useQuery()

After that, implement useEffect to monitor any modifications in the data property and execute the desired effect.

Answer №2

It is important to note that calling React hooks from the `useEffect` hook's callback function is not allowed.

A helpful resource for understanding this concept can be found at trpc.useQuery, which acts as a thin wrapper around Tanstack's useQuery. By moving the query invocation, like `trpc.children.getWeight.useQuery({childId:activeChildId});`, to the top-level and passing the appropriate query options, you can ensure that the query is triggered when the `childId` becomes available. Refer to the documentation on Dependent Queries for more information.

For example:

const { data: weight } = trpc.children.getWeight.useQuery(
  // query input
  { childId: activeChildId },
  // options
  {
    enabled: !!activeChildId
  },
);

In general, it is considered a React anti-pattern to copy data or store derived data by storing `data` in the local `weight` state instead of directly referencing `data`. However, if you do need to keep a local copy of the fetched data that can be updated independently from the queried data, you can use `useEffect` to synchronize the state.

const [weight, setWeight] = useState<ChildWeightDataType[]>([]);

const { data } = trpc.children.getWeight.useQuery(
  // input
  { childId: activeChildId },
  // options
  {
    enabled: !!activeChildId
  },
);

useEffect(() => {
  if (data) {
    setWeight(data);
  }
}, [data]);

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

leveraging the tsconfig path for the source directory in the Next.js Image component

I'm attempting to store the path of my assets folder in the tsconfig file and then use it in the src attribute of the Image component, but for some reason it's unable to locate the address! This is what's in my tsconfig.js file: "paths ...

Troub3leshooting Circular Dependency with Typescript, CommonJS & Browserify

I am currently in the process of transitioning a rather substantial TypeScript project from internal modules to external modules. The main reason behind this move is to establish a single core bundle that has the capability to load additional bundles if an ...

Deactivate the chosen tab by clicking the Mat-Tab button

I was trying to implement a way to disable the selected mat-tab and its elements when a button is clicked, //HTML <mat-tab-group #tabGroup> <mat-tab *ngFor="let subject of subjects" [label]="subject.name"> {{ subject.name }} ...

Is there a way to inform the List component when the height of its row items has been altered in order to trigger a rerender

In my project, I am using a react-virtualized List where each item in the rows has an expand button. When this button is clicked, the row's height changes to reveal more information. The problem I am facing is that after clicking the button, the inne ...

Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice I am developing an angular application that fetches data from an API and presents it on the page The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls apiservice.service.ts ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

I am looking for guidance on how to effectively utilize a JSON object that is stored in the constructor of my component, particularly when triggering

Below is the object I have in my constructor. I am passing a value from a previous component to the one below. I receive the item json object, but I need to use it when I click. constructor(public navCtrl: NavController, public navParams: NavParams) { ...

It is not possible to utilize a JavaScript function once the script has been loaded through

I am attempting to programmatically load a local JavaScript file - PapaParse library, and then utilize one of its functions: $.getScript("./Content/Scripts/papaparse.js", function () { console.log("Papaparse loaded successfully"); Papa.parse(file, ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

Angular mistakenly redirects to the local host at port 4200 with a hash symbol

After using this.router.navigate(['newcard']);, the URL loads correctly but then quickly redirects to localhost:4200/#. This is how I am redirecting from the showcard component to the newcard component: <a href="#" class="btn b ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

When importing Next.js but failing to call the function, an error is thrown: "Module not found: Error: Unable to resolve 'dns'"

Everything was running smoothly with my NextJS project until I suddenly encountered a ModuleNotFoundError issue, specifically related to dynamic routing in NextJs. The error message I am seeing is: Module not found: Error: Can't resolve 'dns&apo ...

What causes the error "Failed to load SWC binary for win32/x64" when using getStaticProps?

Encountering an issue while using getStaticProps() in a Next.js application, resulting in the following error when running the app: warn - Attempted to load @next/swc-win32-x64-gnu, but it was not installed warn - Attempted to load @next/swc-win32-x64-ms ...

Exploring FileReader in conjunction with React and Typescript

I am facing an issue while trying to upload a JSON file using an input element of type file. When I attempt to use the onload method on FileReader in TypeScript, I receive an error message saying "Cannot invoke an object which is possibly 'null'. ...

By default, apply the active class to the initial element in the list and update the active class upon clicking in Next.js

As a newcomer to React, I am struggling with setting the active class in my CSS file. I have two classes, btn and active. My goal is to assign the active class to the first button by default and then switch it to the currently clicked button when interacti ...

What is the method for altering the state of a single element within a map?

As I delve into learning React, I encountered a persistent issue that has been absorbing my time for several hours now. The problem revolves around mapping an array of product sizes to buttons and controlling the state change of only the last clicked butto ...

How can Multer library be effectively utilized to manage exceptions in NestJS controllers?

While working on creating a service to upload specific files from a Post multipart/form-data request, I came across an easy way to validate the fields count and name sent using the FileInterceptor decorator from @nestjs/platform-express. However, I'm ...

Containerize the CMS and NextJS applications and manage their dependencies efficiently. NextJS requires the CMS to be up and running in order to build

Scenario I am currently in the process of dockerizing my application which consists of a headless CMS (Strpi) and a client NextJS. NextJS requires the CMS to be up and running in order to build successfully (as it fetches content from port 1337) Source C ...

Guide on resizing the Image element's height in Next.js

Three images with varying size ratios are sent from the server to me, and my goal is to resize them based on their height. I am currently utilizing the Image component from next.js within a designated container. ...

Exploring the integration of multiple HTTP requests in Angular with the power of RxJS

Is there a way to make multiple HTTP calls simultaneously in an Angular service and then combine the responses into one object using RxJS? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; im ...