Fetch Javascript

Basic Syntax

fetch(url, options)
	.then(response => {
		// handle response
	})
	.catch(error => {
		// handle error
	});

Example 1: Fetching data from an API (GET request)

fetch('https://jsonplaceholder.typicode.com/posts/1')
	.then(response => response.json()) // convert response to JSON, returns a promise
	.then(data => console.log(data)) // handle the data
	.catch(error => console.error('Error:', error));

Example 2: Sending data (POST request)

fetch('https://jsonplaceholder.typicode.com/posts', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': `Bearer ${token}`
	},
	body: JSON.stringify({
		title: 'foo',
		body: 'bar',
		userID: 1,
	}),
})
	.then(response => response.json()) // convert response to JSON, returns a promise
	.then(data => console.log(data)) // handle the data
	.catch(error => console.error('Error:', error));

Example 3: Abort Controller

const controller = new AbortController()
fetch('https://jsonplaceholder.typicode.com/posts/1', 
	  {
		  signal: controller.signal,
	  })
	.then(response => response.json()) // convert response to JSON, returns a promise
	.then(data => console.log(data)) // handle the data
	.catch(error => console.error('Error:', error));

// to cancel the request
controller.abort();

Resources