Basic Concept
-
Fetch
returns aPromise
that resolves toResponse
console.log(fetch("https://reqres.in/api/users")); /* Promise {<pending>} - [[PromiseStatus]]: "resolved" - [[PromiseValue]]: Response */
-
The
Response
objectfetch("https://reqres.in/api/users").then((res) => console.log(res)); /* Response {type: "cors", url: "https://reqres.in/api/users", redirected: false, status: 200, ok: true, …} */
-
.then
orasync-await
-
.then
fetch("https://reqres.in/api/users") .then((res) => res.json()) .then((data) => console.log(data)); /* {page: 1, per_page: 6, total: 12, total_pages: 2, data: Array(6), …} */
-
async-await
async function getFetch() { const response = await fetch("https://reqres.in/api/users"); const data = await response.json(); console.log(data); } getFetch(); /* {page: 1, per_page: 6, total: 12, total_pages: 2, data: Array(6), …} */
-
-
How to check if
Fetch
succeeded?-
Fetch
only fails when there is a failure in itself- bad network connection
- browser cannot connect to the internet
-
Fetch
succeeds even when- 404 response = failure of response
-
Check success of
Fetch
fetch("https://reqres.in/api/users/") .then((res) => { if (res.ok) { console.log("SUCCESS"); return res.json(); } else { console.log("Not Successful"); } }) .then((data) => console.log(data)); /* {page: 1, per_page: 6, total: 12, total_pages: 2, data: Array(6), …} */
async function getFetch() { const response = await fetch("https://reqres.in/api/users"); if (response.ok) { const data = await response.json(); console.log(data); } else { console.log("Not Successful"); } } getFetch(); /* {page: 1, per_page: 6, total: 12, total_pages: 2, data: Array(6), …} */
-
POST Method with Fetch
fetch("https://reqres.in/api/users/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "User 1",
}),
})
.then((res) => {
return res.json();
})
.then((data) => console.log(data))
.catch((error) => console.log("ERROR"));
Fetch
optionsmethod
: "POST"headers
: { "Content-Type": "application/json" }- the data being sent is
JSON
- the data being sent is
body
: JSON.stringify({ name: "User 1" })- change the format of object being sent to
JSON
- change the format of object being sent to
-
async-await
+Fetch
postFetch = async () => { const url = "https://reqres.in/api/users/"; const settings = { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name: "USER 1", }), }; try { const postResponse = await fetch(url, settings); if (postResponse.ok) { const data = await postResponse.json(); console.log(data); } else { console.log("Not Successful"); } } catch (e) { console.log(e); } }; postFetch();