Blog>
Snippets

Client-side parallel fetching with SWR

Using SWR for client-side data fetching in parallel from multiple resources, and displaying the data in a Next.js component.
import useSWR from 'swr';

// Custom fetcher function using fetch API
const fetcher = url => fetch(url).then(res => res.json());

function DataDisplayComponent() {
  // Use SWR to fetch data from multiple endpoints in parallel
  const { data: dataA, error: errorA } = useSWR('/api/dataA', fetcher);
  const { data: dataB, error: errorB } = useSWR('/api/dataB', fetcher);

  if (errorA || errorB) return <div>Error loading data.</div>;
  if (!dataA || !dataB) return <div>Loading...</div>;

  // Display dataA and dataB
  return (
    <div>
      <h1>Data A</h1>
      <pre>{JSON.stringify(dataA, null, 2)}</pre>
      <h1>Data B</h1>
      <pre>{JSON.stringify(dataB, null, 2)}</pre>
    </div>
  );
}

export default DataDisplayComponent;
This code creates a Next.js component called DataDisplayComponent. It uses two instances of the useSWR hook to fetch data from two separate API endpoints ('/api/dataA' and '/api/dataB') in parallel. If there's an error, it displays an error message. If the data is loading, it shows a loading message. Once both API calls have completed successfully, it displays the returned JSON data. The fetcher function is a wrapper around the fetch API that returns JSON.