Getting data in console but shows undefined in main output - javascript

I'm working on a app with electron using axios to get api data, but when i use to display data it shows undefined in screen and when i output it, it shows the correct value!! Some help would be appreciated!
const electron = require('electron');
const path = require('path');
const BrowserWindow = electron.remote.BrowserWindow;
const axios = require('axios');
const notifyBtn = document.querySelector('.notify-btn');
const price = document.querySelector('.price');
const targetPrice = document.querySelector('.target-price');
function getBTC(){
axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD&api_key={api_key}')
.then(function(response) {
let cryptos = response.data;
price.innerHTML = '$'+cryptos;
console.log(response.data);
});
}
getBTC();
setInterval(getBTC, 30000);
I get a output in console:
Object: USD: 3560.263(Current price of bitcoin)
I get output on main screen:
'undefined'
I think its because it an object so how can i display an object?
I may be wrong!!
ThankYou!!

It's not
price.innerHTML = '$'.cryptos;
// but
price.innerHTML = '$' + cryptos.USD;
Add .USD because cryptos is an object. And the value is saved into the key USD

You are accessing the property of a string.
price.innerHTML = '$'.cryptos;
^^^ property
I think you wanted to concat values with a + operator
price.innerHTML = '$' + cryptos;

try using
price.innerHTML = '$'+cryptos.USD;

What are you trying to achieve with '$'.cryptos; ?
If you are trying to concatenate some strings this is not how it works!
try "$"+cryptos

You should use only primitive type variables when composing a string.
If you want to show an object, you could simply use JSON.stringify(cryptos) to obtain the JSON string of the whole object.
Otherwise, you could print any other object property that is a primitive type, like cryptos.USD.

Related

how to access the key in json object in react

I am getting the object below its in json form. i wanted to access only user key from the below object. I tried destructuring the object but didnt got expected value;
const logg=window.localStorage.getItem("userInfo");
const {user}=logg;
console.log(user);
console.log(logg.user);
console.log(logg);
{"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"ss#sss.com","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"}
For the data you actually posted at the bottom of your Q, it would be a simple dereference:
const logg = {"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"ss#sss.com","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"};
const user = logg.user;
console.log(user);
But if it's still in string form like Alaa said, then you need to do:
const logg = '{"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"ss#sss.com","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"}';
const user = JSON.parse(logg).user;
console.log(user);
The item is in string format try JSON parsing it const {user}=JSON.parse(yourString)

how to extract substring from an environment variable

In postman response I have something similar to this
"References": [
"Ref/6789",
"Id/1234"
],
I want to set values 6789 and 1234 to different variables. I am using
let response = pm.response.json();
let bookref = response.References + '';
pm.environment.set("bookref", bookref);
// this sets bookref to Ref/6789,Id/1234
pm.environment.set("ref", bookref.split(',')[1]);
pm.environment.set("id", bookref.split(','));
Both the last 2 lines are failing with
ReferenceError: ref is not defined.
What is missing here? I have tried using .toString() function as well but it failed.
Try this one.
let ref = bookref[0].split('/')[1] ;
let id = bookref[1].split('/')[1] ;
pm.environment.set("ref", ref );
pm.environment.set("id", id );

How to get a param from the url?

I have a url like this:
http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262
I need to get the param called "codice" from the url of this page and use it in a query. I tried with this code:
render() {
const params = new URLSearchParams(this.props.location.search);
const codiceHash = params.get('codice');
console.log(params.get('codice'))
return (
<div className={styles}>
<div className="notification">
<h2>Prima Registrazione eseguita con successo</h2>
</div>
{this.saveEsegue(email, transactionHash , blockHash, now, "FR", codiceHash)}
</div>
)
}
But what I get back from the console.log is null.
What am i doing wrong?
Your URL is invalid. You cannot have # and then later two ? in it.
Your ?codice shoould be &codice
Here is one way to get at codice
const invalidHref = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262&somethingelse"
const codice = invalidHref.split("codice=")[1].split("&")[0];
console.log(codice)
Here is how it would have worked on a valid URL
const params = new URLSearchParams("http://localhost:3000/#/firstregistration?panel=4&codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262")
const codice = params.get("codice")
console.log(codice)
The parameters string isn't correct in the URL, but to get the string from what you've provided I'd use RegEx.
This way it doesn't matter where the codice parameter is in the URL (ie you can add more parameters without breaking it. RegEx will just pick it out.)
const url = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262"; // window.location.href;
const codice = url.match(/(codice=)([a-zA-Z0-9]*)/)[2];
console.log(codice) // prints fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262
I suggest you to use the module querystring to achieve that, this is one of the top used for this purpose.
Example:
console.log(this.props.location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
Since you only want the one parameter and you know which values it can hold I would use regex.
var r = /codice=([a-z0-9]+)&/g
var matches = r.exec('http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262')
console.log(matches[1])
>> fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262
The code snippet will return
codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262
change url_string to window.location.href to grab the current URL of the page
var url_string = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262"; //window.location.href
var b = url_string.substring(url_string.indexOf("?codice=") + 1);
console.log(b);

How to pull in data by using a data-attribute?

I'm trying to pull in data from our API with a data- html trick.. I can call the data directly and it load just fine. But when i try to get the data variable from the data attribute it won't work.
Is there something flawed in my code?
i.e.
<span id="totalBalanceBTC" data-api-user-getbalance="totalBalance">--</span>
function dataAPI() {
let balanceUrl = 'https://api.example.io/v1/user/getbalance/username';
let balanceApiData = getApiData(balanceUrl);
$('[data-api-user-getbalance]').each(function (){
let dataUserBalance = $(this).data("api-user-getbalance");
let data = balanceApiData.dataUserBalance;
// WORKS
$(this).html(balanceApiData.totalBalance);
// DOES NOT WORK
$(this).html(balanceApiData.dataUserBalance);
});
}
1. jQuery's .data() drops the data- prefix and converts the remaining hyphenated string to camelCase, using the dashes as delimiters. It should be:
let dataUserBalance = $(this).data("apiUserGetbalance");
2. To access an object property using a variable, you'll need to use bracket notation. Otherwise you're trying to get the property "dataUserBalance", which doesn't exist.
let data = balanceApiData[dataUserBalance];
const balanceApiData = { totalBalance: 500 };
const $elem = $("#totalBalanceBTC");
let dataUserBalance = $elem.data("apiUserGetbalance");
let data = balanceApiData[dataUserBalance];
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="totalBalanceBTC" data-api-user-getbalance="totalBalance"></span>

How to concat buffers with delimiter in node.js?

I'm trying to concat two buffers with a space in between them in Node.js.
Here is my code.
var buff1 = new Buffer("Jumping");
var buff2 = new Buffer("Japang");
var buffSpace = new Buffer(1);
buffSpace[0] = "32";
var newBuff = Buffer.concat([buff1, buffSpace, buff2], (buff1.length + buff2.length + buffSpace.length));
console.log(newBuff.toString());
As per official doc, the first argument will be the Array list of Buffer objects. Hence I've created buffSpace for space.
Class Method: Buffer.concat(list[, totalLength])
list : Array List of Buffer objects to concat
totalLength: Number Total length of the buffers when concatenated
I'm getting the result as expected but not sure whether it is right way to do so. Please suggest if any better solution to achieve the same.
There are three changes I would suggest.
First, if you are using Node v6, use Buffer.from() instead of new Buffer(), as the latter is deprecated.
Second, you don't need to pass an argument for totalLength to Buffer.concat(), since it will be calculated automatically from the length of all of the buffers passed. While the docs note it will be faster to pass a total length, this will really only be true if you pass a constant value. What you are doing above is computing the length and then passing that, which is what the concat() function will do internally anyway.
Finally, I would recommend putting this in a function that works like Array.prototype.join(), but for buffers.
function joinBuffers(buffers, delimiter = ' ') {
let d = Buffer.from(delimiter);
return buffers.reduce((prev, b) => Buffer.concat([prev, d, b]));
}
And you can use it like this:
let buf1 = Buffer.from('Foo');
let buf2 = Buffer.from('Bar');
let buf3 = Buffer.from('Baz');
let joined = joinBuffers([buf1, buf2, buf3]);
console.log(joined.toString()); // Foo Bar Baz
Or set a custom delimiter like this:
let joined2 = joinBuffers([buf1, buf2, buf3], ' and ');
console.log(joined2.toString()); // Foo and Bar and Baz
Read the Buffer stream and save it to file as:
const data = [];
req.on('data', stream => {
data.push(stream);
});
req.on('close', () => {
const parsedData = Buffer.concat(data).toString('utf8');
fs.writeFileSync('./test.text', parsedData);
});

Categories

Resources