#is there a different approach of using useQuery in a function so it doesnt error
3 messages · Page 1 of 1 (latest)
Let me check the knowledge base for you. One moment! :books:
Yes, there are different approaches to handle errors when using useQuery in a function.
One approach is to use an error boundary to catch the error in a parent element or write a custom hook to return the error object. This is how useQueries works, it returns either undefined for loading, a Convex value, or an error object. Try/catch doesn't make sense in React components because like an if statement it causes hooks to be run conditionally which isn't allowed by the rules of hooks. source (https://discord.com/channels/1019350475847499849/1184579377858629732)
Another approach is to use the <Authenticated> component to wrap any component that needs to call authenticated queries. This way, the query would never run or happen if the user is not authenticated. source (https://discord.com/channels/1019350475847499849/1214577747570204673)
Here's an example of how to use the <Authenticated> component:
import { Authenticated, Unauthenticated, AuthLoading } from "convex/react";
function AuthenticatedApp() {
const r = useQuery(api.myquery);
return <div>{r}</div>;
}
function App() {
return (
<div className="App">
<Authenticated><AuthenticatedApp /></Authenticated>
<Unauthenticated><MyLoginComponent/></Unauthenticated>
<AuthLoading>Still loading</AuthLoading>
</div>
);
}