How to Use Fetch in TypeScript ?
Last Updated :
30 Jul, 2024
In TypeScript, fetching the data from any server or API using fetch() API is not the same as we used to do it in Plain or Vanilla JavaScript. Let us see how we can use the fetch API to fetch data from any server or API in TypeScript.
NOTE: Before using this code, please make sure that you have jQuery installed in your project folder or work directory.
Syntax:
async function func_name(url: string): Promise<any>{
const response = await fetch(api_url, method/request type, [other_params]);
const data = await response.json();
return data;
}
Approach
- Create an HTML file with the name index.html to structure our web page.
- Use the different HTML elements like div, heading, paragraph, etc to structure our web page.
- Now, create an index.ts file to write the TypeScript code for using the fetch API.
- Use a random API that provides the random data with the fetch API to fetch the data using the GET request.
- Create the dynamic HTML to show the fetched data to the user on the screen.
Example 1: The below code example uses the fetch API with async await and the try-catch blocks to fetch data and display it to the user by generating dynamic HTML.
HTML
<!-- index.html file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<title>
Using fetch in TypeScript
</title>
<style>
.app {
text-align: center;
}
.h1 {
font-size: 30px;
color: green;
}
#result {
color: #FF671F;
}
</style>
</head>
<body>
<div class="app">
<h1 class="h1">
GeeksforGeeks
</h1>
<h3 id="result">
Click the below button to fetch
the data of new current user.</h3>
<button id="btn">
Change Current User
</button><br /><br />
<div id="currentUser"></div>
</div>
</body>
</html>
JavaScript
// index.ts file
import $ from 'jquery';
declare var global: any;
global.jQuery = $;
import 'jquery-ui';
async function fetchGET(url: string): Promise<any> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Unable to Fetch Data, Please check URL
or Network connectivity!!`
);
}
const data = await response.json();
return data.results[0];
} catch (error) {
console.error('Some Error Occured:', error);
}
}
async function clickHandler() {
try {
const returnedData =
await fetchGET('https://randomuser.me/api/');
$('#currentUser').html(
`
Current User: <br/><br/>
<img style="border-radius: 50%" src=
${returnedData.picture.medium} alt="User Image"/>
<p>
Name:
<b>
${returnedData.name.title}
${returnedData.name.first}
${returnedData.name.last}
</b>
</p>
<p>
Email:
<b>
${returnedData.email}
</b>
</p>
<p>
Country:
<b>
${returnedData.location.country}
</b>
</p>
<p>
Phone:
<b>
${returnedData.phone}
</b>
</p>
<p>
Gender:
<b>
${returnedData.gender}
</b>
</p>
`);
} catch (error) {
console.error('Some Error Occurred:', error);
}
}
clickHandler();
$('#btn').on('click', clickHandler);
Output: You can see the final output of the project below:
Example 2: The below code example uses the fetch() API without async await and the try-catch blocks.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<title>
Using fetch in TypeScript
</title>
<style>
.app {
text-align: center;
}
.h1 {
font-size: 30px;
color: green;
}
#result {
color: #FF671F;
}
</style>
</head>
<body>
<div class="app">
<h1 class="h1">
GeeksforGeeks
</h1>
<h3 id="result">
Click the below button to fetch
the data of new current user.</h3>
<button id="btn">
Change Current User
</button><br /><br />
<div id="currentUser"></div>
</div>
</body>
</html>
JavaScript
import $ from 'jquery';
declare var global: any;
global.jQuery = $;
import 'jquery-ui';
function fetchGET(url: string): Promise<any> {
return fetch(url).then((response) => {
if (!response.ok) {
throw new Error(
`Unable to Fetch Data, Please check
URL or Network connectivity!!`
);
}
return response.json();
})
.then((data) => data.results[0])
.catch((error) => console.log(error));
}
async function clickHandler() {
try {
const returnedData =
await fetchGET('https://randomuser.me/api/');
$('#currentUser').html(`
Current User: <br/><br/>
<img style="border-radius: 50%" src=
${returnedData.picture.medium} alt="User Image"/>
<p>
Name:
<b>
${returnedData.name.title}
${returnedData.name.first}
${returnedData.name.last}
</b>
</p>
<p>
Email:
<b>
${returnedData.email}
</b>
</p>
<p>
Country:
<b>
${returnedData.location.country}
</b>
</p>
<p>
Phone:
<b>
${returnedData.phone}
</b>
</p>
<p>
Gender:
<b>
${returnedData.gender}
</b>
</p>
`);
} catch (error) {
console.error
('Some Error Occurred:', error);
}
}
clickHandler();
$('#btn').on('click', clickHandler);
Output:
You can see the final output of the project below:
Similar Reads
How to use express in typescript ? In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nod
2 min read
How to use TypeScript on backend ? TypeScript, developed by Microsoft, enhances JavaScript by adding type safety, which significantly simplifies debugging and development. This guide will walk you through setting up a TypeScript backend with Node.js and Express, showing you how to leverage TypeScriptâs robust features to prevent comm
2 min read
How to Use NextJS in Typescript? TypeScript enhances Next.js applications by adding static type checking and improves developer experience through type safety. Integrating TypeScript into your Next.js project helps catch errors early and improves code maintainability. It offers even greater productivity and robustness to your web d
5 min read
How to use Try Catch and Finally in TypeScript ? The try, catch and finally blocks are used for error handling and state management while performing asynchronous tasks. It is an effective way to handle errors and state on the web page. This tutorial will explain to you the use of the try, catch, and finally statements practically.Explanation:try:
2 min read
How to use TypeScript with React? TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
3 min read