Blog>
Snippets

Edge runtime data-fetching with SWR

Show how to perform server-side data-fetching in an Edge function using SWR for stale-while-revalidate caching strategy.
// Importing required modules from 'swr' and 'node-fetch'
import useSWR from 'swr';
import fetch from 'node-fetch';

// A fetcher function that will be used by SWR to fetch data
const fetcher = async (url) => {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('An error occurred while fetching the data.');
  }
  return response.json();
};

// Inside your component or hook where you want to use SWR
function useEdgeData(url) {
  // Using SWR to fetch data with a stale-while-revalidate strategy
  const { data, error } = useSWR(url, fetcher);

  return {
    data: data,
    isLoading: !error && !data,
    isError: error
  };
}
This code snippet demonstrates the import of required modules, creation of a fetcher function that handles fetching data from an external source, and the `useEdgeData` function that uses SWR (Stale-While-Revalidate) for data fetching in an edge runtime environment by utilizing the fetcher. The useEdgeData function returns the fetched data, a loading state, and an error state.