#UseQuery is definetly going to return result and not null or undefined

4 messages · Page 1 of 1 (latest)

fallow ibex
#

@hybrid zinc is there a way to usequery so result is gurantee and no null or undefined value

hybrid zincBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, there are a few ways to handle this situation in Convex.

  1. Check for undefined to determine if a query is loading: The useQuery React hook will return undefined when it is first mounted, before the query has been loaded from Convex. Once a query is loaded it will never be undefined again (even as the data reactively updates). You can use this as a signal for when to render loading indicators and placeholder UI. source (https://docs.convex.dev/production/best-practices#check-for-undefined-to-determine-if-a-query-is-loading)

  2. Use a custom hook to skip undefined states: You can create a custom hook called useStableQuery that functions similarly to useQuery but keeps track of the resulting data with React’s builtin useRef hook. This allows you to only update the value returned from useStableQuery once the query result is no longer undefined. Here's an example of how you can implement this:

// hooks/useStableQuery.ts

import { useRef } from 'react'
import { useQuery } from '../convex/_generated/react'

export const useStableQuery = ((name, ...args) => {
 const result = useQuery(name, ...args)

 // useRef() creates an object that does not change between re-renders
 // stored.current will be result (undefined) on the first render
 const stored = useRef(result) 

 // After the first render, stored.current only changes if I change it
 // if result is undefined, fresh data is loading and we should do nothing
 if (result !== undefined) {
 // if a freshly loaded result is available, use the ref to store it
 stored.current = result
 }
#

// undefined on first load, stale data while reloading, fresh data after loading
return stored.current
}) as typeof useQuery // make sure we match the useQuery signature & return type

**source** (<https://stack.convex.dev/help-my-app-is-overreacting#impacting-how-the-querys-reacting>)

3. **Use a wrapper hook with Suspense**: You could implement a wrapper hook on top `useQuery` that works with Suspense. This hook would resolve a promise when the data is no longer `undefined`, allowing you to handle loading states with React's Suspense feature. **source** (<https://discord.com/channels/1019350475847499849/1138164674362347562>)

Remember, `undefined` is not a valid return type for queries in Convex. If a query actually returns `undefined`, it will show up as `null` in the client, so `undefined` can only mean loading. **source** (<https://discord.com/channels/1019350475847499849/1156630144463687710>)
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------