fetch in JavaScript
fetch in JavaScript: Getting Data with fetch, When fetch Fails, Loading, Empty and Error States, Sending Data with fetch.
Updated
- Getting Data with fetch (Apprentice): fetch sends a request to a web API and gives back a promise of the response; await it, then await response.json() to turn the JSON answer into a JavaScript value your page can use.
- When fetch Fails (Journeyman): fetch rejects only when no answer arrives at all, so check response.ok for answers like 404 and 500, catch network errors and timeouts (AbortSignal.timeout) with try/catch, and turn each one into a message a person understands.
- Loading, Empty and Error States (Journeyman): A page that loads data has four states, loading, success, empty and error, and it should say which one it's in, so people never stare at a blank screen or a page that quietly broke.
- Sending Data with fetch (Journeyman): To send data to an API, give fetch a second argument with method POST, a Content-Type header that says the body is JSON, and a body made with JSON.stringify; and know that CORS, the API's rule about which sites may call it, decides whether a page can call it at all.