Fetches Flashcards
(16 cards)
Common elements of a fetch request in vanilla JS
- try {} catch(error) {} blocks
- OPTIONS: method, body (JSON.stringify(data), headers (content-type)
LINE BY LINE SYNTAX
const response = await fetch(‘https://api.example.com/data’);
const data = await response.json();
console.log(data);
THEN => THEN => SYNTAX
fetch(‘https://api.example.com/data’, OPTIONS)
.then(response => response.json())
.then(jsonData => console.log(jsonData))
.catch(error => console.error(‘Error fetching data:’, error));
Common elements of a fetch request specifically in ReactJS
- “use client”
- state for managing the data and error message
- useEffect to run the fetch function on first load (if not on click)
- fetch function that includes setting the states for data / errors
Compare REST API and Fetch API on their architecture and HTTP methods
ARCHITECTURE
REST is an architectural style for designing networked applications.
Fetch is a JS interface for making HTTP requests.
FETCH API
REST relies on HTTP methods for accessing resources.
Fetch supports these methods and can interact with REST APIs.
What are Promises and how are they related to fetch?
The fetch method returns a Promise. Promises must be handled with either .THEN or AWAIT syntax. Only if the Promise returned is RESOLVE the next line will be read. If the server is down or if there is another error (caught with .CATCH syntax) then the Promise returned is REJECT.
What is the history of Fetch API? What was before it?
It was introduced in 2015 as part of ES6. It improves upon XHR with cleaner syntax such as .then() instead of adding event listeners to a request object (e.g. “load”).
Prior to Fetch API XMLHttpRequest (XHR) was used for async network requests. XHR had some drawbacks (can’t abort requests, complex callbeck hell syntax).
What arguments are there in the fetch API function?
First argument: url
Second argument: options (for headers, HTTP method, data)`
What happens if you console.log a fetch call?
You get a Promise {<pending>}</pending>
What are the two main ways to handle a Promise?
ASYNC AWAIT
.THEN()
What happens when you console.log a fetch?
e.g. fetch(url).then(res => console.log(res))
You get a Response object containing various things including….
- status code
- status text
- ok: true/false
- body: readableStream (i.e. JSON data that must be parsed)
, and a few other things….
How do you get from the fetch’s response to data you can read in JavaScript?
You need to use the built-in response.json() method that automatically converts the readableStream in a Response object to JS.
e.g. fetch(url).then(res => console.log(res)).then(data => console.log(data))
How would you do error handling with fetch?
The simplest way is just with the res.ok attribute.
fetch(url).then(res => {if (res.ok) {log(“Success”) else { log(“Fail”).then(data => log(data)).catch(error => log(error)
What are the HTTP status code bands?
1xx=informational
2xx= successful
3xx= redirection
4xx= client error (eg bad syntax)
5xx= server error
What are the most common HTTP status codes?
200 OK
403 Forbidden
404 Not Found
405 Method Not Allowed
500 Internal Server Error
503 Service Unavailable
Axios as an alternative - what are the cons?
Requires installation
Increases bundle size
Axios as an alternative - what are the pros?
Simpler syntax
Better error handling
Auto-parsing JSON
Timeouts on fetch requests/Request cancellation (much easier)