Middle
How to organize polling of the user list every 15 seconds using TanStack Query (React Query)? Which function to use and with what parameters?
sobes.tech AI
Answer from AI
To set up polling with TanStack Query (React Query), the refetchInterval option is used in the useQuery hook. It specifies the interval in milliseconds at which the query will automatically repeat.
Example for polling a list of users every 15 seconds:
import { useQuery } from '@tanstack/react-query';
function fetchUsers() {
return fetch('/api/users').then(res => res.json());
}
function UsersList() {
const { data, error, isLoading } = useQuery(['users'], fetchUsers, {
refetchInterval: 15000, // 15 seconds
refetchIntervalInBackground: true, // optional, to poll even if the tab is inactive
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Thus, useQuery with refetchInterval allows automatic data refresh on a timer.