Handling dependent react queries

I have two react queries in the same component

const { data: sdrData, status: sdrDataLoading } = useQuery(
    [queryInfo[0]?.dcsSysId, data[0]?.dcsStructSysId, data[cardIndex]?.dcsStructNodeId],
    () => getSDR(queryInfo[0]?.dcsSysId, data[0]?.dcsStructSysId, data[cardIndex]?.dcsStructNodeId),

  const { isIdle, data: sdrTemplateData, status: sdrTemplateDataLoading } = useQuery(
    [sdrData[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId],
    () =>
      SDRTemplateValues(sdrData[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId, {
        // The query will not execute until the userId exists
        enabled: !!sdrData[0]?.dcsSdrSysId,
        retry: true,

My second query is depended on the first I need to access sdrData[0] for the first arg in my query however when I do this the query is undefined initially and it fails. Is there a good way to handle this. I saw you can set it equal to a variable, but I’m still faced with the same problem.

I need a way to tell the first query to wait until the second query is finished before it tried to access the arguments. I thought you could set enabled like I did, but that didn’t work either.


I was able to solve this by adding the data parameter I need to the beginning of the argument array like this.

const { data: sdrData, status: sdrDataLoading } = useQuery(
    queryInfo[0]?.dcsSysId && [
    () => getSDR(queryInfo[0]?.dcsSysId, data[0]?.dcsStructSysId, data[cardIndex]?.dcsStructNodeId),

  const { data: sdrTemplateData, status: sdrTemplateDataLoading } = useQuery(
    sdrData?.[0]?.dcsSdrSysId && [sdrData?.[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId],
    () => SDRTemplateValues(sdrData?.[0]?.dcsSdrSysId, queryInfo[0]?.fldTemplateSysId),

Leave a Reply

Your email address will not be published. Required fields are marked *