Basic notes on JavaScript Fetch API
Fetch is promise-based, so we should wait for the output // using .then
method or await
keyword.
fetch("https://reqres.in/api/users")
.then(
response => {
response.json().then(
data => {
console.log(data);
}
)
}
)
Fetch will always succeed, so it's important to deal with API-related errors, from response objects using ok
property or status codes.
// #2.
fetch("https://reqres.in/api/users/24")
.then(
response => {
if (response.ok) {
response.json().then(
data => {
console.log(data);
}
)
}
else {
console.log("Request failed.")
}
}
)
If you are sending a POST
request make sure to have headers right and the body is JSON string (not a javascript object).
fetch("https://reqres.in/api/users", {
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({
name: "Named Guy",
job: "Unemployed"
})
}).then(
response => {
if (response.ok) {
response.json().then(
data => {
console.log(data);
}
)
}
else {
console.log("Request failed.")
}
}
)
Use async
& await
keywords to handle promises. When await
keyword is used, execution is paused until promise is resolved. It can only be used inside async
function.
const asnyc_function = async () => {
let res = await fetch("https://reqres.in/api/users");
if (res.ok) {
let data = await res.json();
console.log(data);
}
}
asnyc_function();