psych0groov3
psych0groov3

Reputation: 701

React query useQueries Cannot read properties of undefined (reading 'map')

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?

Upvotes: 0

Views: 1432

Answers (2)

eater
eater

Reputation: 1

i solve my problem with

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

Upvotes: 0

Tomas Vancoillie
Tomas Vancoillie

Reputation: 3868

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

Upvotes: 2

Related Questions