How to manipulate strings inside array from a fetch response? - javascript

I am looking for some assistance with my fetch response from the Online Movie Database API . I am able to succesfully get a response to log in the console, which is what I want. However I am trying to manipulate the response.
I want to pull the most popular shows from the API (API sends 100 titles), and trim it down to 8 titles. I did that using the .splice method. It returns an array of 8 strings representing a title id.
Example: '/title/tt11198330'
Lastly I want to trim each 8 of the strings so it gets rid of the /title/ and all I have left is tt11198330. I am trying to do this inside the .then and when I console.log that forEach that is saved as 'trimmer' it gives me undefined instead of the trimmed result I was intending. But if I console.log the element in the forEach it does show the trimmed strings. Any idea why its undefined, and is there maybe a better way to go about this?
// fetch for most popular shows
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'Z2EvqnO4xwmsh2eY3rMTIV2ivj5hp1QsuGUjsnrYp69UBS4EI5',
'X-RapidAPI-Host': 'online-movie-database.p.rapidapi.com'
}
};
fetch('https://online-movie-database.p.rapidapi.com/title/get-most-popular-tv-shows?currentCountry=US&purchaseCountry=US&homeCountry=US', options)
.then(response => response.json())
.then(response => {
const list = response.splice(0, 8)
let trimmer = list.forEach(element => console.log(element.slice(7, 17)))
console.log(trimmer)
})
.catch(err => console.error(err));

because you are using forEach and it doesn't return data, use map instead.
fetch('https://online-movie-database.p.rapidapi.com/title/get-most-popular-tv-shows?currentCountry=US&purchaseCountry=US&homeCountry=US', options)
.then(response => response.json())
.then(response => {
const list = response.splice(0, 8)
let trimmer = list.map(element => element.slice(7, 17))
console.log(trimmer)
})
.catch(err => console.error(err));

Related

How to get as variable and display in html particular info from javascript console.log?

I have a task to get and display in html a particular data from API result (console.log). For now on, I only have a javascript that gets exchange rates with currency conversion. From fetched data I only need currency rate.
var myHeaders = new Headers();
myHeaders.append("apikey", "r4T22n3O14QL7FoG6FzY7FuUHTNXiKAy");
var requestOptions = {
method: 'GET',
redirect: 'follow',
headers: myHeaders
};
//var rslt = console.log(result);
fetch("https://api.apilayer.com/currency_data/convert?to=RUB&from=EUR&amount=1", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Here is the result I get in console.log
and my problem is that I cannot display : 1. anything from that log to HTML and 2. particular data (rates) from that log.
this is the console log I am getting:
{
"success": true,
"query": {
"from": "EUR",
"to": "RUB",
"amount": 1
},
"info": {
"timestamp": 1658378463,
"quote": 56.217115
},
"result": 56.217115
}
I need to get a rates/"quote" as a variable in order to use it elsewhere.
Thank you in advance.
Use response.json() and then extract the properties that you want into variables.
fetch("https://api.apilayer.com/currency_data/convert?to=RUB&from=EUR&amount=1", requestOptions)
.then(response => response.json())
.then(json => {
let quote = json.info.quote;
document.getElementById("quote").innerText = quote;
})
.catch(error => console.log('error', error));
Replace "quote" with the actual ID of the element where you want to show the quote.
To display value using HTML, you need to use Template literals concept in javascript. You can set elements with a unique ID in HTML. Using HTML DOM Element innerHTML Property and Template Literals you can achieve.
Particular data (rates) from that log:
let rate = result.result;
As I mentioned above you will get the rate result.
Assuming you have something like
<div id="quote"></div>
in your html,
I would do something like this:
.then(response => response.json())
.then(data => { document.getElementById('quote').innerHTML = data.info.quote})
.catch(error => console.log('error', error));
see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I've got the answer !
const render = data => {
const rate = document.querySelector(".rate")
rate.innerHTML = (data.info.rate).toFixed(2);
}
const init = url => {
fetch(url).then(resp => resp.json()).then(render)
}
init("https://api.exchangerate.host/convert?from=EUR&to=RUB")
and of course this is another API provider, but anyway, this is the simplest way to get and manipulate with currency rate data.
Thanks for everyone's attempt :)

Firebase push get key with sdk 9 modular approach

As the question asks I'm attempting to get the key after I push to a firebase db.
push(dbRef, formState)
.then((resp) => {
console.log(resp);
})
.catch(error => {
Alert.alert(error)
})
The above console.log gives me the full url of the data pushed. In example:
"https://example.firebaseio.com/organization/asdfasdfasdf/members/-N08ScImBoOckVIRu-AU". I need the key only: `-N08ScImBoOckVIRu-AU`
I incorrectly attempted:
push(dbRef, formState)
.getKey()
.then((resp) => {
})
.catch(error => {
Alert.alert(error)
})
This gives an error.
How can I accomplish this?
If you split the push() call from the actual writing of the data, you can get the key like this:
const newRef = push(dbRef);
console.log(newRef.key);
set(newRef, formState);

Is is possible to read a .csv file with Javascript fetch API?

Like
fetch('state_wise_data.csv')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
Tried doing this but didn't work.
First of all, CSV it's not a JSON. Fetch does not have CSV support, you will need to download CSV string (you can use response.text()) and use the third party CSV parser.
For parse CSV parser you can use papaparse:
"Isn't parsing CSV just String.split(',')?"
Heavens, no. Papa does it right. Just pass in the CSV string with an optional configuration.
Example:
const response = fetch('state_wise_data.csv')
.then(response => response.text())
.then(v => Papa.parse(v))
.catch(err => console.log(err))
response.then(v => console.log(v))
It also supports file downloading:
Papa.parse('state_wise_data.csv', {
download: true,
complete: results => {
console.log(results);
}
})
Fetch is 100% work with .csv file (or even api with req.query).
'content-type': 'text/csv' must be addressed in the fetch's headers:{}, and use res.text() instead of res.json() to interpret data.
const downloadCsv = async () => {
try {
const target = `https://SOME_DOMAIN.com/data/csv/addresses.csv`; //file
//const target = `https://SOME_DOMAIN.com/api/data/log_csv?$"queryString"`; //target can also be api with req.query
const res = await fetch(target, {
method: 'get',
headers: {
'content-type': 'text/csv;charset=UTF-8',
//'Authorization': //in case you need authorisation
}
});
if (res.status === 200) {
const data = await res.text();
console.log(data);
} else {
console.log(`Error code ${res.status}`);
}
} catch (err) {
console.log(err)
}
}
CSV is not a JSON file type, so you cant parse as a json text. you can check how to parse CSV text in javascript here : Example JavaScript code to parse CSV data
I would use the following method and insert it where you are supposed console.log the data.
const parseCSV = (data) => {
// create empty array
const csvData = [];
// this will return each line as an individual String
const lines = data.split("\n");
// loop through the lines and return an array of individual
// Strings within the line that are separated by a comma
for (let i = 0; i < lines.length; i++) {
csvData[i] = lines[i].split(",");
}
// return an array of arrays 2D array
// e.g [ [1,2,3], [3,4,5], [6,7,8] ]
return csvData;
};
pretty easy,
GET the url, with normal fetch req, and first convert response to text and then it's done
fetch('sample-url.csv')
.then((response) => response.text())
.then((data) => console.log(data));

Saving data from JSON end point

I am trying to map over the returned json and save the id into profile/profiles. However it does not seem to be mapping over the the data correctly, id: ${ profile.id } this bit needs to be changed? Any help is much appreciated.
Is their a online tool that can help with me this?
API request:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data.map(profile => ({
id: `${ profile.id }`
}))
)
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
Json data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
When I console log the response.data
If the only data returned from your endpoint is the JSON you posted, then you don't have an array to map over.
You have a single object.
I've never used the axios library before, but looking at the source code response.data should be the JSON-parsed responseText from the XHR request:
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/adapters/xhr.js#L51-L53
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/defaults.js#L61
And now I see that you have posted response.data and it matches what I'd expect.
With that in mind I'd suggest handling it like this:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => ({
id: profile.id
}))
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
What you're getting back is a single profile though. If you need profiles to be an array you'll need to put the response in an array.
I don't get it, what you are trying to do. In the map you have a callback function, but as I see you wrote there an object. If you are wanting to rewrite the current profile's id then write this:
response.data.map(profile => ({
profile.id = `${ profile.id }`;
}))
But if you want it to make a variable then this:
response.data.map(profile => ({
let id = `${ profile.id }`;
}))

fetch JSON works in node but fails in broser (JSON.parse unexpected end of data at line 1 column 1)

I'm trying to get a json file from an api, when using this code on node.js it works perfectly fine and I can see the results I'm looking for, but when I try to use it from the browser it fails and returns with the error message on the title.
async function searchVolumes(volume, url, apiKey) {
let result = await fetch(url, {mode: 'no-cors'})
.then(res => res.json())
.then(json => json.results)
.catch(error => console.log('Error reading data ' + error))
return result
}
I've tried it in Firefox and Edge and have the same problem in both of them, but checking the network tab I can see the result and the json is fine with no errors, and as I say at the beginning it works on node too.
I modified it according to sideshowbarker links and removed the no-cors mode and added a proxy cors anywhere server and it's working now:
const proxy = 'https://cors-anywhere.herokuapp.com/'
url += proxy
async function searchVolumes(volume, url, apiKey) {
let result = await fetch(url)
.then(res => res.json())
.then(json => json.results)
.catch(error => console.log('Error reading data ' + error))
return result
}

Categories

Resources