Rune DarkfireR
Convex Community16mo ago
5 replies
Rune Darkfire

How do I wait for a useQuery declaration to return before proceeding?

I feel like I'm missing something simple. Here's the code for a component that gets called on many pages in my application :
  const { isLoaded, isSignedIn, orgId } = useAuth();

  const contractTypes = useQuery(api.contract_types.list, { orgId: orgId !== undefined ? orgId : undefined }) || []
  const addContractType = useMutation(api.contract_types.add)
  const vendorCategories = useQuery(api.vendor_categories.list, { orgId: orgId !== undefined ? orgId : undefined }) || []
  const addVendorCategory = useMutation(api.vendor_categories.add)

  const settingsLoaderRef = useRef(false);

  useEffect(() => {
    if (!settingsLoaderRef.current && isLoaded && isSignedIn && orgId
        && contractTypes && vendorCategories) {
      settingsLoaderRef.current = true // EXECUTION GETS HERE BUT contractTypes AND vendorCategories are returning the empty array, even though I know they should have data in them
      if (!contractTypes.length) setContractTypeDefaults()
      if (!vendorCategories.length) setVendorCategoryDefaults()
    }
  }, [isLoaded, isSignedIn, contractTypes, vendorCategories, orgId]);

How can I make this useEffect do what I want so that the vendorCategories and contractTypes tables in the DB don't keep adding the defaults over & over? To be clear -- the very first time this code is called after a login, it behaves as if the arrays are empty, but when I navigate away from any pages with this component and then come back, it recognizes what's in the DB at that point. How do I make sure it loads what's in the DB from the useQuery the FIRST time this is called after login?
Was this page helpful?