swr fetcher in typescript

Here's how you can use useSWR with TypeScript and fetch data:

index.ts
import useSWR from 'swr';

type Data = {
  // define the shape of your data
  foo: string;
  bar: number;
};

const MyComponent: React.FC = () => {
  const { data, error } = useSWR<Data>('/my-api-endpoint', async url => {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('Failed to fetch data');
    }
    return response.json();
  });

  if (error) return <div>Failed to load data</div>;
  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <p>{data.foo}</p>
      <p>{data.bar}</p>
    </div>
  );
};
557 chars
28 lines

Here, we define Data type for our fetched data, which defines the shape of our data. In the useSWR hook, we pass this type as a generic argument. The useSWR hook takes two arguments: the first argument is the endpoint to fetch, and the second argument is an async function that fetches the data from the endpoint. In this function, we check if the response is ok, and return the JSON data. Once the data is fetched, we render the component based on whether there is an error or not, and whether the data is loaded or not.

gistlibby LogSnag