#is there a different approach of using useQuery in a function so it doesnt error

3 messages · Page 1 of 1 (latest)

brisk axle
#

@obtuse niche is there a different approach of using useQuery in a function so it doesnt error

obtuse nicheBOT
#

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>
  );
}

Remember to always use useQuery for queries (readonly, reactive data loading) and useMutation for mutations (read-write, imperative actions). source (https://discord.com/channels/1019350475847499849/1218746843064963082)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: