useswr fetching from api in typescript

To fetch data from an API in TypeScript, we can use the built-in Fetch API. Here is an example of how to make a GET request to an endpoint and get the response as JSON:

index.ts
async function fetchData() {
  try {
    const response = await fetch('https://example.com/api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
    // Handle error here
  }
}
237 chars
11 lines

In this code, we first use the fetch function to make a GET request to the URL 'https://example.com/api/data'. The fetch function returns a Promise that resolves to the response object.

We then use the json method of the response object to extract the JSON data from the response. The json method also returns a Promise that resolves to the parsed JSON data.

Finally, we wrap this code in an async function so we can use the await keyword to wait for the responses before returning the data.

If there is an error during the fetch, we catch it and handle it appropriately.

It is also important to properly type the data being fetched and the response object to ensure type safety throughout our codebase.

gistlibby LogSnag