When to use "src/page/api/doStuff.ts" vs "src/server/api/routers/routerThatDoesStuff.ts"

I am trying to get data from a db AFTER I click a button. Correct me if i am wrong - to do this, you would use a useEffect that is dependent on a useState boolean, once true, inside the useEffect you do the fetching My 1st screenshot is the page/api option My 2nd is tRPC use query (the option i want to use).
I like the api route because I only call the api WHEN I CLICK THE BUTTON, but the second option (tRPC T3 way) I call it even before the button is clicked. Just would like to know if I am doing the tRPC T3 way correctly or if there is a better way. Thanks 🙂
No description
No description
6 Replies
dan
dan•15mo ago
don’t do the first one. use effect for fetching data is always a bad idea. If you only want to conditionally fetch data with trpc either use the enable prop on the hook, or use a mutation which gets triggered by the button on click. also don’t eslint ignore the use effect dep. it’s there for a reason, listen to it.
jeff.kershner
jeff.kershner•15mo ago
Hello... as you know, you can't call a hook conditionally. But in react-query (and tRPC), you can supply an enabled parameter on when you want to call that useQuery. For example:
const bill = api.sale.bill.useQuery(
{rows: spreadSheet?.rows ?? [] },
{ refetchInterval: false, refetchOnWindowFocus: false, enabled: hasBilled });
const bill = api.sale.bill.useQuery(
{rows: spreadSheet?.rows ?? [] },
{ refetchInterval: false, refetchOnWindowFocus: false, enabled: hasBilled });
This useQuery will only be executed if hasBilled is true. This is a typical pattern that is used when submitting a form. When clicking submit, you change a local state variable to true and use that variable in the enabled flag. Does this answer your question?
cadams
cadamsOP•15mo ago
Trying this code below gives this error Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. const { data: billedFromServer } = api.sale.bill.useQuery({ rows: spreadSheet?.rows ?? [] }, { refetchInterval: false, refetchOnWindowFocus: false, enabled: hasBilled }); if (billedFromServer) { setHasBilled(false); setBillResultt(billedFromServer); } thanks for the advice! i have tried the enabled way, but get this error above ^ .... but trying the useMutation way now ....
cadams
cadamsOP•15mo ago
This seems to work well and code looks okay too i think, what do you think ?
No description
cadams
cadamsOP•15mo ago
I am still wondering about the title of this thread - does "src/server/api/routers" make "src/page/api" redudant ?
dan
dan•15mo ago
you update the state when the component renders and updating state causes a rerender. What specifically are you trying to do in this component?
Want results from more Discord servers?
Add your server