tRPC Error: Invalid hook call.
Sorry for the noob question I just cant figure out how to do this I have the following tRPC route:
export const appsRouter = createTRPCRouter({
search: publicProcedure.input(z.string()).query(async ({ input, ctx }) => {
console.log("input", input);
return await ctx.prisma.app.findMany({
where: {
name: {
search: input,
},
},
});
}),
getAll: publicProcedure.query(async ({ ctx }) => {
return await ctx.prisma.app.findMany();
}),
});
I am trying to call the search route from a function in my home page but it keeps throwing Invalid Hook call. I tried wrapping it in React.useEffect but still get the same error:
const data = api.appsRouter.getAll.useQuery().data;
const [apps, setApps] = React.useState<Array<AppType>>();
const [searchTerm, setSearchTerm] = React.useState<string>("");
React.useEffect(() => {
if(data){
setApps(data);
}
}, [data]);
React.useEffect(() => {
if(searchTerm){
const filteredData = api.appsRouter.search.useQuery(searchTerm).data;
if(filteredData){
setApps(filteredData);
}
} else {
setApps(data);
}
}, [searchTerm, data]);
const [showLimit, setShowLimit] = React.useState(8); const handleSearch = (search: string) => { setSearchTerm(search); }
const [showLimit, setShowLimit] = React.useState(8); const handleSearch = (search: string) => { setSearchTerm(search); }
6 Replies
hooks must only be called at the top level and never conditionally (they should run every time, in the same order)
also you shouldnt be creating local proxy state that just shadows the query
just use
data
from the query and derive whatever you need from it just in a variable
should follow this kind of patternI was trying to offload the search compute to the database server for "filtering" I had some logic for fuzzy search on the client side but was really interested to see if it was possible to dynamically call aa tRPC route based on a client event i.e onClick/onKeyPress similar to an async function calling await fetch is there a pattern I can use to make that possible because there will be some upcoming component work that will need something similar. I was looking into building dynamic page routes i.e feed the data to the url and then render the whole page that way but it seemed inefficient.
Use a mutation
Call mutate within the event handler
I can write an example later if you want
Stack Overflow
tRPC invalid hook call in react function component
I am trying to create a new user when the user connects to the site with their wallet.
When the user clicks the button to connect, the useAccount hook will return an address of type string.
I then ...
ahhh ok sorry i thought mutations were just when you modify data but i see now I was mistaken. Thanks for the answer!
also thank you @cje for the example