TanStackT
TanStack2y ago
4 replies
uncertain-scarlet

Problem with react query and nextjs query params

Hi, I am using react query with a custom hook for pagination but the query is not executed, it is always pending for some reason and it does not make the call, is it because of the line where I push the queries, did it happen to anyone?
import { OptionalParams, Pagination } from '@/types/commonTypes'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { useEffect, useState } from 'react'

const usePagination = (otherParams: OptionalParams = {}) => {
  const searchParams = useSearchParams()
  const router = useRouter()

  const defaultParams: Pagination = {
    page: Number(searchParams?.get('page')) || 1,
    limit: Number(searchParams?.get('limit')) || 10,
    search: searchParams?.get('search') || '',
  }

  const [query, setQuery] = useState<Pagination & OptionalParams>({
    ...defaultParams,
    ...otherParams,
  })

  useEffect(() => {
    const newParams = new URLSearchParams(searchParams)
    Object.entries(query).forEach(([key, value]) => {
      if (value !== undefined && value !== '') {
        newParams.set(key, value !== null ? value.toString() : '')
      }
    })
    router.push(`?${newParams.toString()}`)
  }, [query, currentPathname, router, searchParams])

  return {
    query,
    setQuery,
  }
}

export default usePagination

is for this line, if i delete it react query works but dosent push to the url
router.push(`?${newParams.toString()}`)



const { query, setQuery } = usePagination()

  const { data: milestones, isLoading } = useQuery({
    queryKey: ['getMilestonesByProject', '', query],
    queryFn: () => getMilestonesProject('', query),
  })
error.png
Was this page helpful?