JavaScript:Fetch
lastmod 2024-01-06created 2019-08-149 edits
The Fetch API defines an interface for fetching resources, including across the network. Similar APIs such as XMLHttpRequest exist, but the new Fetch API allows more powerful and flexible operations.
POST Example
const obj = {
body: ...,
headers: {},
method: 'POST'
}
fetch(URL, obj)
.then(res => res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err));
Making Fetch abortable
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
fetch(`/api/users/${id}`, {signal})
.then(res => res.json())
.then(data => {
setUser(data);
});
return () => {
controller.abort();
};
}, [id])
Timeout
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 8000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
}
// ...
async function loadGames() {
try {
const response = await fetchWithTimeout('/games', {
timeout: 6000
});
const games = await response.json();
return games;
} catch (error) {
// Timeouts if the request takes
// longer than 6 seconds
console.log(error.name === 'AbortError');
}
}