0

I need to provide a parameter for the function call within useInfinityQuery, where this parameter will hold a value used for filtering in the request URL parameters.

My parameter is named "search_query."

export function useGetCustomers() {
  async function getCustomerApi(pageParam: number, search_query: string) {
    const response = await api.get<ApiResponse>(
      `/users?page=${pageParam}&search=${search_query}`,
    )
    return response.data
  }

  const { data, fetchNextPage, hasNextPage, isFetching, isInitialLoading } =
    useInfiniteQuery<ApiResponse>(
      ['customers'],
      async ({ pageParam = 1 }, search_query = '') =>
        getCustomerApi(pageParam, search_query),
      {
        keepPreviousData: false,
        getNextPageParam: (lastPage) => {
          return lastPage.next_page_url
            ? lastPage.next_page_url.split('=')[1]
            : null
        },
      },
    )

  return {
    customers: data?.pages.flatMap((page) => page.data),
    getNextPageCustomers: fetchNextPage,
    hasNextPageCustomers: hasNextPage,
    isFetchingCustomers: isFetching,
    isInitialFetchingCustomers: isInitialLoading,
  }
}

In the component, I'm trying to call the request function in this way:

  useEffect(() => {
    getNextPageCustomers({search_query:"Josh"})
  }, [])

However, it's not working; this variable is arriving with the value undefined. How can I resolve this?

LayTexas
  • 545
  • 2
  • 6
  • 19

1 Answers1

0

You should pass this property as an argument directly to the hook.

export function useGetCustomers(search_query: string)
  async function getCustomerApi(pageParam: number, search_query: string) {
    const response = await api.get<ApiResponse>(
      `/users?page=${pageParam}&search=${search_query}`,
    )
    return response.data
  }

  const { data, fetchNextPage, hasNextPage, isFetching, isInitialLoading } =
    useInfiniteQuery<ApiResponse>(
      // add search_query to the cache key so the cache works correctly
      ['customers', search_query],
      // search_query is not passed as an argument
      // but read directly from the enclosing scope
      async ({ pageParam = 1 }) =>
        getCustomerApi(pageParam, search_query),
      {
        keepPreviousData: false,
        getNextPageParam: (lastPage) => {
          return lastPage.next_page_url
            ? lastPage.next_page_url.split('=')[1]
            : null
        },
      },
    )

  return {
    customers: data?.pages.flatMap((page) => page.data),
    getNextPageCustomers: fetchNextPage,
    hasNextPageCustomers: hasNextPage,
    isFetchingCustomers: isFetching,
    isInitialFetchingCustomers: isInitialLoading,
  }
}
  const { getNextPageCustomers } = useGetCustomers("Josh")

  useEffect(() => {
    getNextPageCustomers()
  }, [])
Anton
  • 1,045
  • 1
  • 7
  • 16