Blog>
Snippets

Synchronization Between Route Transitions and Data Fetching States

Demonstrate how to coordinate complex state transitions, such as data refetching upon navigating to a new route using React Query, with visual feedback for loading states.
import { useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';

function fetchData(key) {
  // simulate fetching data from an API
  return new Promise(resolve => setTimeout(() => resolve('Data fetched!'), 2000));
}
Defines a function to simulate fetching data from an API using setTimeout for a 2-second delay, and imports necessary hooks from react-query and react-router-dom.
const App = () => {
  const navigate = useNavigate();
  const { isLoading, data, refetch } = useQuery('dataKey', () => fetchData('data'), {
    enabled: false // disable automatic refetching on mount
  });

  const handleNavigate = (path) => {
    refetch().then(() => navigate(path));
  };

  return (
    <div>
      <button onClick={() => handleNavigate('/new-route')}>Go to new route</button>
      {isLoading && <p>Loading...</p>}
      {!isLoading && <p>{data}</p>}
    </div>
  );
}
Creates a React component that uses the useNavigate hook to change routes and the useQuery hook from React Query to manage the data fetching state. The 'enabled: false' option prevents automatic data refetching when the component mounts, allowing explicit control over fetching. The handleNavigate function refetches data before routing.