Discover 8 tricks for using the Fetch() API, including streaming data, monitoring download progress, and cancelling streams with the Abort Controller. Explore the benefits of streaming data, like generating progress indicators and cloning web streams. Also learn about consuming the Response object multiple times and handling JSON errors.
Read more
AI Summary
AI Chapters
Episode notes
auto_awesome
Podcast summary created with Snipd AI
Quick takeaways
Streaming the result allows you to start processing the data while it continues to download, useful for downloading large files.
By utilizing the AbortController, you can now cancel fetch requests, especially useful for handling autocomplete text searches or switching requests.
Deep dives
Streaming the Result
When making a fetch request, the initial response does not necessarily contain the complete data. Streaming the result allows you to start processing the data while it continues to download. This is useful, for example, when downloading large files like an mp3. By accessing the stream in the response, you can begin processing and streaming in the data as it arrives, such as displaying progress to the user.
Canceling Fetch Requests
You can now cancel fetch requests by utilizing the AbortController. By creating an AbortController and passing its signal to `fetch`, you can later call `controller.abort()` to stop the request. This is particularly useful when handling autocomplete text searches or when you need to stop a request and switch to another one.
Testing JSON Responses
When working with server-side APIs, it's important to handle cases where JSON may not be returned, such as error messages in HTML format. Instead of calling `response.json()`, which could result in a syntax error, you can use `response.text()` to retrieve the text of the response. Then, you can wrap the `JSON.parse()` in a try-catch to handle any parsing errors, allowing you to properly handle and display errors to the user.
// Create a new TextDecoder instance const decoder = new TextDecoder(); // Make the fetch request fetch('https://api.example.com/streaming-data') .then(response => { // Check if the response is valid if (!response.ok) { throw new Error('Network response was not ok'); } // Stream the response data using a TextDecoder const reader = response.body.getReader(); // Function to read the streamed chunks function read() { return reader.read().then(({ done, value }) => { // Check if the streaming is complete if (done) { console.log('Streaming complete'); return; } // Decode and process the streamed data const decodedData = decoder.decode(value, { stream: true }); console.log(decodedData); // Continue reading the next chunk return read(); }); } // Start reading the chunks return read(); }) .catch(error => { // Handle errors console.log('Error:', error); });
// Create an AbortController instance const controller = new AbortController(); // Set a timeout to abort the request after 5 seconds const timeout = setTimeout(() => { controller.abort(); }, 5000); // Fetch request with the AbortController fetch('https://api.example.com/data', { signal: controller.signal })