Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to I pass a filters variable to useInfiniteQuery with pageParam?

I’m trying to pass the queryKey variable alongside the pageParam in useInfiniteQuery? I’ve tried for a while but:

  • Cannot get the page data
  • In some cases, the data is rendered repeatedly.

How should I pass the variables?

export const fetchInfiniteVariants = async (
  filters = {},
  { pageParam = 0 }
) => {
  const records = await axios.get(baseURL, {
    headers: authHeader,
    params: {
      pageSize: 24,
      offset: pageParam,
      fields: [
        "name",
        "packshot",
        "packshot_size",
        "brand_logo",
        "price",
        "slug",
      ],
      // filterByFormula: `({validated} = 1)`,
      filterByFormula: `(${filterByFields(filters)})`,
      "sort[0][field]": "priority",
      "sort[0][direction]": "asc",
    },
  })
  return records
}

export const useInfiniteVariantsQuery = (
  initialRecords,
  offset,
  filters = { brand: "HAY" }
) => {
  const infiniteVariantsQuery = useInfiniteQuery(
    ["infiniteVariants", filters],
    () => fetchInfiniteVariants(filters),
    {
      initialStale: true,
      staleTime: 6000,
      getNextPageParam: (lastPage, pages) => lastPage.data.offset,
    }
  )
  return {
    ...infiniteVariantsQuery,
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The queryFn you’re passing to useInfiniteQuery has request context as a parameter to that callback, as documented on the useInfiniteQuery page:

Receives a QueryFunctionContext object with the following variables:

  • queryKey: EnsuredQueryKey: the queryKey, guaranteed to be an Array
  • pageParam: unknown | undefined

You can destructure and retrieve your queryKey from that, as below:


export const useInfiniteVariantsQuery = (
  initialRecords,
  offset,
  filters = { brand: "HAY" }
) => {
  const infiniteVariantsQuery = useInfiniteQuery(
    ["infiniteVariants", filters],
    ({ queryKey, pageParam }) => fetchInfiniteVariants(queryKey[1], pageParam),
    {
      initialStale: true,
      staleTime: 6000,
      getNextPageParam: (lastPage, pages) => lastPage.data.offset,
    }
  )
  return {
    ...infiniteVariantsQuery,
  }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading