Jei
Jei3w ago

Invalid hook call using useQuery

Hello, I am trying to implement a common component that accepts a function props that will fetch data from the server. For example, see the code below:
export const UsersTable = () => {
return (
<CommonComponent
fetchData={async (pageIndex, pageSize) => {
const { data } = api.users.list.useQuery({ pageIndex: 0, pageSize: 10 }); // api is created in another file which `api = createTRPCReact<x>();`
}}
/>
)
}
export const UsersTable = () => {
return (
<CommonComponent
fetchData={async (pageIndex, pageSize) => {
const { data } = api.users.list.useQuery({ pageIndex: 0, pageSize: 10 }); // api is created in another file which `api = createTRPCReact<x>();`
}}
/>
)
}
The reason that I want to do this is so that I can reuse the <CommonComponent> in other files where I need to only replace the query with another query to fetch different data from the server. I know this violates the rules of hook, but just wondering if there is any other way to fetch the data from the server which is not a hook (using trpc)? I have tried using refetch but seems like it is not allowing me to take in a new input, for example I want to update the pageIndex and pageSize, refetch doesn't allow me to input the new values. Thanks in advance!
3 Replies
Alex / KATT 🐱
you want to do something like
export const UsersTable = () => {
const utils = trpc.useUtils()
return (
<CommonComponent
fetchData={async (pageIndex, pageSize) => {
const res = await utils.users.list.fetch(/*...*/)
// [...]
} />
)
}
export const UsersTable = () => {
const utils = trpc.useUtils()
return (
<CommonComponent
fetchData={async (pageIndex, pageSize) => {
const res = await utils.users.list.fetch(/*...*/)
// [...]
} />
)
}
Alex / KATT 🐱
useUtils | tRPC
useUtils is a hook that gives you access to helpers that let you manage the cached data of the queries you execute via @trpc/react-query. These helpers are actually thin wrappers around @tanstack/react-query's queryClient methods. If you want more in-depth information about options and usage patterns for useContext helpers than what we provide h...
Jei
Jei3w ago
Thanks! Didn't know there is useUtils available. Really appreciate that