0

I have the following hook to fetch multiple queries:

function useClientSurveys(surveysIds) {
  const { isAdmin } = useAdminStatus();
  return useQueries(
    surveysIds &&
      surveysIds.map(surveyId => ({
        queryKey: ['clientSurvey', surveyId],
        queryFn: () => getSurvey(surveyId),
        enabled: !isAdmin && !!surveysIds,
      }))
  );
}

I'm using it like this:

  const dummyIds = [
    '1234534324326',
    '3487236482376'
  ]

  const {
    data: clientSurveys,
    isError: isClientSurveysError,
    isLoading: isClientSurveysLoading,
  } = useClientSurveys(dummyIds);

I keep getting undefined even though I know the array is defined because it's hard-coded in this case.

What may be causing this error?

2 Answers 2

2

As described in the documentation, you need to pass your queries as an object.

useQueries({
  queries: surveysIds.map(surveyId => ({
    queryKey: ['clientSurvey', surveyId],
    queryFn: () => getSurvey(surveyId),
    enabled: !isAdmin && !!surveysIds,
  }))
})

UseQueries documentation

Sign up to request clarification or add additional context in comments.

1 Comment

you also need to make sure that surveysIds is an array. OP had a check with surveysIds && surveysIds.map(...) and that won't work. It needs to be something like: surveyIds?.map(...) ?? []
0

i solve my problem with

  return useQueries(
      surveysIds.map(surveyId => ({
        queryKey: ['clientSurvey', surveyId],
        queryFn: () => getSurvey(surveyId),
        enabled: !isAdmin && !!surveysIds,
      })) ?? []
  );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.