Here's how you can use useSWR
with TypeScript and fetch data:
index.ts557 chars28 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