Skip to content

Instantly share code, notes, and snippets.

@kamiljozwik
Created November 17, 2021 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamiljozwik/fbeab8bdd9843dd0c2ce217b898ea532 to your computer and use it in GitHub Desktop.
Save kamiljozwik/fbeab8bdd9843dd0c2ce217b898ea532 to your computer and use it in GitHub Desktop.
Split fetch into smaller chunks
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