Created
November 17, 2021 07:00
-
-
Save kamiljozwik/fbeab8bdd9843dd0c2ce217b898ea532 to your computer and use it in GitHub Desktop.
Split fetch into smaller chunks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getData = async () => { | |
/** 1. Everything as one big fetch: */ | |
let res_1 = await fetch('https://icanhazdadjoke.com/search?term=music&limit=3', { | |
headers: { accept: 'application/json' }, | |
}); | |
/** 2. Split above into smaller chunks 🪓 */ | |
/* 2.1. Set search params values */ | |
let term = 'music'; | |
let limit = '3'; | |
/* 2.2. Generate search parameters using "URLSearchParams" API */ | |
let searchParams = new URLSearchParams({ term, limit }); | |
/* 2.3. Create new URL (with search params) using "URL" API */ | |
let url = new URL(`https://icanhazdadjoke.com/search?${searchParams.toString()}`); | |
/* 2.4. Create request's headers using "Headers" API */ | |
let headers = new Headers({ accept: 'application/json' }); | |
/* 2.5. Create request using "Request" API */ | |
let req = new Request(url, { headers }); | |
/* 2.5. Finally, fetch data 🙂 */ | |
let res_2 = await fetch(req); | |
console.log(res_1); | |
console.log(res_2); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment