T
TanStack3y ago
probable-pink

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}
}
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 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)}
</>
)
}
// 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?
2 Replies
absent-sapphire
absent-sapphire3y ago
You create useState twice. Changing it in your first component can’t change the other useState The two useStates are independent of each other. As solutions: put the offset in your URL or in a global state manager like jotai, zustand, …
probable-pink
probable-pinkOP3y ago
Thank you so much, I lift the state up to my zustand, it works now

Did you find this page helpful?