How to fetch data properly for this API? (array) - javascript

console.log screenshot
Hi, I am using "fetch" method with API for my website, and this API shows book information, if books include the input title.
Screenshot attached is console.log result when typing an example book title.
I'd like to get every title info of each array, could anyone can help me on this?
Especially I am not sure what is the proper line for this.
.then((data) => {document.getElementById("bookinfo").innerHTML=
data['documents'.authors];
Entire script for fetch is below.
<script>
function getBook(){
let bookvalue=document.getElementById("book").value;
fetch('https://dapi.kakao.com/v3/search/book?target=title&query=' + bookvalue, {
headers: {
Authorization: "KakaoAK TokenID"
}
})
.then((response) => response.json())
.then((data) => {document.getElementById("bookinfo").innerHTML=
data['documents'.authors];
});
}
</script>

You're not calling the array index correctly, data['documents'.authors] should be data.documents[0].authors to get the author of the first item and data.documents[1].authors to get the second, etc...
What do you intend to do with the titles?
EDIT: Fixed it for easier use (I think this is what you want)
.then(data => data.documents.map(book => book.title)).then(titles => document.getElementById("bookinfo").innerHTML = titles.join(", "));
Otherwise create an array
const titles = [];
push into array
.then(data => data.documents.map(book => titles.push(book.title))
But you might have issues with this and get empty array since the promise might still be pending

Related

API returns JSON? Or something else?

I'm building a simple React app for a class project using the National Weather Service API. The idea is: get an API return for a set of latitude and longitude coordinates (which I'll expand later so that users can input their address and a separate geocoding API can return their lat/long coordinates), which contains the URL to the forecast data (using grid coordinates), use that URL to get a second API return (believe it or not this is how NWS says it should be done) which is an object which contains a nested object properties that contains a nested array periods of objects that each represent a day/night forecast, each identified with a name and number.
I have the following code successfully displaying a list of the period names (to start), but I am getting an error in console: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0.
Internet searches (including stackoverflow) tell me this occurs because the return isn't in JSON format, but all the resources I can find on the NWS API says it returns JSON. If it didn't; I don't think I'd get anything displaying on the web page (right?), so I must be getting JSON back since I'm seeing the period names.
In addition, the names only display when I update the browser that's displaying my live server. If I refresh the page it disappears. What's going on?
import React, { useState, useEffect } from 'react'
function GetForecast() {
const [gridEndpoint, setGridEndpoint] = useState('');
const [forecastArray, setForecastArray] = useState([]);
useEffect(() => {
fetch(`https://api.weather.gov/points/45.5312,-122.6447`)
.then(reply => reply.json())
.then(json => json.properties.forecast)
.then(link => setGridEndpoint(link))
.then(
fetch(`${gridEndpoint}`)
.then(reply => reply.json())
.then(json => json.properties.periods)
.then(array => setForecastArray(array))
)
}, [])
return (
<div>
{forecastArray.map((period, index) => (
<div key={index}>{period.name}
</div>
))}
</div>
)
}
Had someone point out to me that setGridEndpoint() isn't updating gridEndpoint the way I had it written. Here's what I replaced it with.
useEffect(() => {
fetch(`https://api.weather.gov/points/45.5312,-122.6447`)
.then(reply => reply.json())
.then(json => json.properties.forecast)
.then(link => fetch(link))
.then(reply => reply.json())
.then(json => json.properties.periods)
.then(array => setForecastArray(array))
}, [])

Extract the price only from api using node-fetch array

I am sorry for a basic question, I have been trying to extract only the price using node-fetch from API
const fetch = require('node-fetch');
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
.then(res => res.text())
.then(text => console.log(text))
let AvgPrice = text.map(text => text.price);
The error I am receiving is
internal/modules/cjs/loader.js:968
throw err;
^
Please, any suggestion is greatly appreciated
There are several things that you need to check out
Errors reagarding cjs/loader.js have little or nothing to do with your code per se but rather the setup, for example how you run the code, naming of the file, etc,
internal/modules/cjs/loader.js:582 throw err
https://github.com/nodejs/help/issues/1846
This code will return Reference error: text is not defined.
The reason is that you never define the variable text and then you try to call map function on it.
Also fetch is a async function and nodejs is single threaded non-blocking. So what happens is that you send a http request (fetch) to the website, that takes times, but meanwhile your coding is still running, so continues to the next line in your code.
Lets add some console logs
const fetch = require('node-fetch');
console.log('1. lets start')
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
.then(res => res.text())
.then(text => {
console.log('2. I got my text', text)
})
console.log('3. Done')
You might think that this will log out
lets start
I got my text {"mins":5,"price":"0.4998"}
Done
Nopes, it will log out
Lets start
Done
I got my text {"mins":5,"price":"0.4998"}
Because you fetched the data, then your program continued, it looged out 3. Done and THEN when it got the data from api.binance it logged out 2. I got my text (notice the keyword then, it happens later)
map is a function for arrays. What the api returns is an object. So when you fix your async code, you will get TypeError text.map is not a function
Since it returns an object you can access it's property right away text.price

Using data pulled from an API

It's been half a day now of trying to figure this out, and while some progress has been made, and a ton of useful research, I'm still a newbie so I need help.
What I need is to use the data that I'm pulling from an API to use as a JS variable. My API is giving me the following output:
{"bitcoin":{"usd":9695.66,"usd_24h_change":2.0385849528977977}}
I want to use the usd and usd_24_change values from that string, maybe as some JS variable for further calculations.
So far what I've managed to do was to push the string directly in HTML, so I can have a visual representation of it, however I need to pull the values from it in the backend (hope that makes sense?)
My code so far:
fetch(url)
.then(response => response.text())
.then(data => {
$('#apiPlaceholder').html(data);
});
I've honestly ran out of ideas. My only alternative would be trying to pull the values directly from the HTML string but I feel like that would be a really clunky way of doing it. I'm sure there's ways to interpret the data in the backend.
Any ideas would definitely be appreciated! :)
Here's how you would go about doing that:
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data["bitcoin"]["usd"]);
console.log(data["bitcoin"]["usd_24h_change"]);
});
you need to parse the response and then just save it.
fetch(url)
.then(response => response.text())
.then(data => {
const parsedData = JSON.parse(data);
const usd = parsedData.bitcoin.usd;
const usd_24h_change = parsedData.bitcoin.usd_24h_change;
});
or display it instead;

How to use array items as parameter for API call

I am currently trying to log out the names and ID of a various items for a video game using an array which holds the ID of each item.
Currently I have the following.
const URL =
"http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=";
const items = ["4151", "2"];
items.map(item => {
fetch(`${URL}${item}`)
.then(data => data.json())
.then(({ item: { id, name } }) => console.log(`${id}: + ${name}`));
});
I should be getting 4151: Abyssal Whip as a format for each item, but it isnt working. I have done this in the past using a cryptocurrency api, but I cant get it to work here, and I am not sure where I am going wrong.
Thanks for the help in advance.
Some more detail would help. If you open dev tools and look at console output when hitting the API, you might be getting an error... maybe a Mixed-Content error? The runescape API is returning from an HTTP connection. If you are requesting from an HTTPS connection, it will not allow the resource to be delivered. Otherwise, your code should run (but the +) won't be necessary because you're using template literals.
I am sure its a typical CORS policy error. Here's how I managed to fetch the data. The heroku API enables cross-origin requests to anywhere.
const items = ["4151", "2"];
const proxyUrl = "https://cors-anywhere.herokuapp.com/",
targetUrl =
"http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=";
items.map((item) => {
fetch(proxyUrl + targetUrl + item)
.then((data) => data.json())
.then(({ item: { id, name } }) => console.log(`${id}: + ${name}`));
});

Getting response data out of Fetch blob from Wikipedia api

I'm trying to use Wikipedia's api with fetch.
const endpoint = 'https://en.wikipedia.org/w/api.php?
action=query&format=json&origin=*&titles=Albert%20Einstein'
fetch(endpoint)
.then(blob => blob.json())
.then(data => console.log(data))
RETURNS
I'm not sure how to drill down in this, due to that 736. I assume there is nothing there? What do these results mean?
I did these loops to see if they allowed me something I could not get by clicking in the console. It's the same as fetch call above so not really useful. Just wanted to show that I tried something at least (downvote control).
fetch(endpoint)
.then(blob => blob.json())
.then((data) => {
for(var i in data){
//returns batch complete ,
//& query
for(var j in data.query){
//returns pages
for(var k in data.query.pages){
//returns the string 736
}
}
}
})
Does nothing more than clicking the console results above.
Use formatversion=2 for a slightly more comfortable format (where data.query.pages is an array).
Alternatively, you could iterate the object with something like
var pages = data.query.pages;
for (pageId in pages) {
if (pages.hasOwnProperty(pageId)) {
console.log(pages[pageId]);
}
}
In modern browsers you can also use Object.values() to get the properties of the object in an array.

Categories