TanStackT
TanStack3y ago
4 replies
skinny-azure

single useQuery in multiple components

Hi Folks,

So as title says it's pretty straight forward I have a useQuery that fetch a pagination data

const useGetUserDetail = () => {
  const router  = useRouter()
  const id = router.query.id
    const [offset, setOffset] = useState(0)
    const {data} = useQuery({
      queryKey: ['useGetUserDetail', id , offset],
      queryFn: () => axios.get(`/api/users/${id }?offset=${offset}`)
    })
  
    return {data, setOffset}
}


It is pretty straight forward, now I use it in different component, componentA and componentB. In componentA user can click to change the offset, and componentA and B will render the data

// Component A
const ComponentA = () => {
  const {setOffset, data}  =useGetUserDetail()
  return (
  <>
  <button onClick={() => setOffset(prev => prev + 1)}>click</button>
  {JSON.stringigy(data)}
  </>
  )
}


// Component B
const ComponentB = () => {
  const {data}  =useGetUserDetail()
  return (
  <>
  {JSON.stringigy(data)}
  </>
  )
}


For some reason the componentB data is not updated, I usually use this pattern and data always sync, but when doing this click button the data is not sync, anyone know why?
Was this page helpful?