fetch pure javascript handling promises - javascript

return fetch(url)
.then(response => response.json())
.then(json => {
//everything just here?
})
.catch(err => console.log(err));
Hello guys i have a newbie question. If i want to get some data from server and manage them (create new html elements, draw some canvas) am i forced to do it this way in ".then" chain? Im asking because its quite unintuitive. And ill be glad for some example of code like this, just get data from server and create/edit some html elements. Thanks!

You can do it in more intuitive way like this
getDataFromServer(url) {
return fetch(url)
.then(response => response.json());
}
async yourMainFunction() {
const data = await getDataFromServer(url);
////everything just here with data from server?
}
one thing to note that for using await you have to make your function marked with async

You are correct, the only place the response json is avalable is in the second then() callback.
You could create a function that contains your html/canvas logic and then call that function in the response callback.
fetch(url)
.then(response => response.json())
.then(json => {
handleResponse(json) // ⭐️
})
.catch(err => console.log(err));
function handleResponse (json) {
// ⭐️ everything in here
}

Related

API fetch console log doesn't print properly

When using fetch method for API, does anyone know why .then(response => console.log(response.originator.name)) doesn't print any value?
console.log(response)
console.log(response.content) and console.log(response.originator.name)
I was trying to find answers for this but haven't had any luck so far. Any information would be appreciated.
function getQuote(){
fetch('https://quotes15.p.rapidapi.com/quotes/random/', options)
.then(response => response.json())
.then(response => console.log(response.content))
.then(response => console.log(response.originator.name))
.catch(err => console.error(err));}
The problem is that you put the second console.log() in a second .then(). This is receiving the result of the first console.log(), but console.log() doesn't return anything (and if it did return something, it would presumably be the object that it logged, not response). Put them both in the same .then().
function getQuote() { fetch('https://quotes15.p.rapidapi.com/quotes/random/', options)
.then(response => response.json())
.then(response => {
console.log(response.content);
console.log(response.originator.name);
})
.catch(err => console.error(err));
}

How can i use my data from a api and pass it into another function for further processing

What method is there without using setTimeout() to allow data from the fetch to be stored in the stored_data array, then allowing the test function to manipulate.
So far i get undefined.
let stored_data = []
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => stored_data.push(json))
function test(e) {
console.log(e)
}
You could simply chain another .then. You also forgot to declare store_data as a variable
let stored_data = []
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => stored_data.push(json))
.then( _ => {
// array now ready for manipulation
})

Promises chain incorrect. Doesn't return multiple values

I want to return two values from a fetch request:
stats.videoCount
stats.viewCount
Using the following code, I can return one value correctly, but cannot return both.
The following code returns the video view count.
fetch("https://api.promptapi.com/tiktok/hashtag/planttrees", requestOptions)
.then(response => response.json())
.then(treeViewCountResult => console.log(treeViewCountResult.challengeInfo.stats.viewCount))
.catch(error => console.log('error', error))
But this code won't return two values:
.then(response => response.json())
.then(treeVideoResult => console.log(treeVideoResult.challengeInfo.stats.videoCount))
.then(treeViewCountResult => console.log(treeViewCountResult.challengeInfo.stats.viewCount))
.catch(error => console.log('error', error))
treeVideoResult and treeViewCountResult will work individually, but not together.
How am I chaining the promises incorrectly?
It returns a single object. You don't need two then for it.
fetch("https://api.promptapi.com/tiktok/hashtag/planttrees", requestOptions)
.then(response => response.json())
.then(result => console.log(result.challengeInfo.stats.videoCount, resutl.challengeInfo.stats.viewCount))
I think you're misunderstanding what's happening with each then.
Everything in the example works up to this line:
.then(treeVideoResult => console.log(treeVideoResult.challengeInfo.stats.videoCount))
The result of response.json() is being given to the then function as treeVideoResult, a property of which, is being logged by console.log. However console.log returns undefined.
This means that in this line:
.then(treeViewCountResult => console.log(treeViewCountResult.challengeInfo.stats.viewCount))
treeViewCountResult is undefined. So it should throw an error (although I haven't checked).
If we want to return multiple values from one fetch call, consider using an object.
fetch("https://api.promptapi.com/tiktok/hashtag/planttrees", requestOptions)
.then((response) => response.json())
.then((treeVideoResult) => ({
videoCount: treeVideoResult.challengeInfo.stats.videoCount,
viewCount: treeVideoResult.challengeInfo.stats.viewCount,
}))
.then((result) => {
console.log(result);
doSomthingElseFunction(result);
})
.catch((error) => console.log("error", error));
TLDR: the return of one then is the input of the next. Any function using the data returned by fetch must be called inside a then (if not using async/await).

Display a response from a Fetch with HTML?

My goal is to display some data on a webpage that I have obtained with a Fetch using HTML.
My Fetch (which works) looks like this
<script>
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => console.log(response.events[0].title));
</script>
The code works and logs a response to the console as I've requested. Now, I'd like to show some of the response on my webpage.
My attempts have looked something like this
<center><h2 id="response"></h2></center>
<script>
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => console.log(response.events[0].title))
.then((response) => {
document.getElementById("response").innerHTML = response.events[0].title;
});
</script>
Context and details:
I've done some mobile dev, but I'm a noob with even basic HTML/JS interaction on web so there are some holes in my knowledge here
I'll be implementing this code injection as a code block on a Squarespace (Adirondack template, Adirondack family) but I don't think the Squarespace context should matter (the Fetch works just fine, and the code injection has been displaying other things just fine)
Error from my attempt: VM22305 about:srcdoc:8 Uncaught (in promise) TypeError: Cannot read property 'events' of undefined
I'm not committed to any particular way of displaying, I'm just trying to get the ball rolling by seeing something on the page
Thanks for your help!
Your second then is console logging and returning nothing (console.log returns undefined), so in the next then statement the response is undefined.
Change your code to:
<center><h2 id="response"></h2></center>
<script>
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => {
console.log(response.events[0].title);
return response;
})
.then((response) => {
document.getElementById("response").innerHTML = response.events[0].title;
});
</script>
And it should work.
If you want a chain of thens, you need to return a promise to the next one, like this:
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => {
document.getElementById("response").innerHTML = response.events[0].title;
});

Fetching API and return Specific data

So, I am trying to fetch API from Calendarific I fetch it and I get data in console here is the code below:
btn.addEventListener('click', function fetchApi(){
fetch('https://calendarific.com/api/v2/holidays?&api_key=<myKey>&country=US&year=2019')
.then(res => res.text())
.then(data => {
//holiday.innerHTML = data;
//console.log(data);
console.log(data.holidays[0].name)
})
.catch(err => console.log(err));
// alert('click')
});
But I want to access specific data like. I want to access only the name and how can I do that? Code works fine but I faced problem to access specific data from API I tried holidays[0].name But it shows undefined What I am doing wrong here?
When receiving JSON, instead of
.then(res => res.text())
.then(...
use
.then(res => res.json())
.then(...
Also, according to calendarific documentation, there's a response key you should query first:
console.log(data.response.holidays[0].name)

Categories

Resources