nextjs useswr in typescript

To use useSWR with TypeScript in a Next.js project, you can start by installing the required dependencies:

npm install swr axios
22 chars
2 lines

Then, you can create a new TypeScript file for your component and import the required modules:

import { useState } from 'react';
import useSWR from 'swr';
import axios from 'axios';

type Data = {
  // Define your data type here
};

const fetcher = (url: string) => axios.get<Data>(url).then(res => res.data);

const MyComponent = () => {
  const [query, setQuery] = useState<string>('default');
  const { data, error } = useSWR<Data>(`/api/data?query=${query}`, fetcher);

  if (error) return <div>Error: {error.message}</div>;
  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)} />
      <pre>{JSON.stringify(data)}</pre>
    </div>
  );
};

export default MyComponent;
658 chars
27 lines

In this example, we're using useState to manage the state of an input field that allows the user to update the query parameter. We're also defining a Data type to represent the shape of the data returned by the API.

The fetcher function takes a URL and returns a Promise that resolves to the data returned by axios.get. We're using axios to make the HTTP request, but you can swap this out with whatever library you prefer.

Finally, we're passing the URL and fetcher function to the useSWR hook. This will return an object with data and error properties that represent the state of the data fetch.

Note that we're using generics to specify the shape of the data returned by the API. You can customize this to match your API response.

That's it! With these steps, you should be able to use useSWR with TypeScript in your Next.js project.

gistlibby LogSnag