I am getting an undefined when trying to use the search bar in my app. The components compile fine in webpack. I am not sure if I am having an es6 syntax issue or am missing something inside the operation of the components.
const axios = require('axios');
const OPEN_WEATHER_MAP_URL =
'http://samples.openweathermap.org/data/2.5/weather?appid=5d0a2ef2cca550311d7015dc03763d54&units=imperial';
module.exports = {
getTemp(location) {
var encodedLocation = encodedURIComponent(location);
var requestUrl = `${OPEN.WEATHER_MAP_URL}&q=${encodedLocation}`;
axios.get(requestUrl).then((res) => {
if (res.data.cod && res.data.message) {
throw new Error(res.data.message)
} else {
return res.data.main.temp;
}
((res) => {
throw new Error(res.data.message);
})
})
}
};
I get the error when I trigger the search in the search bar I get the undefined at var encodedLocation = encodedURIComponent(location);
I have tried using let and const instead of var, but this also did not help
Fix a small typo:
Change
var encodedLocation = encodedURIComponent(location);
to
var encodedLocation = encodeURIComponent(location);
Related
Is there a way to use const { data } = await axios.get(insertthinghere); multiple times?
Trying to use AXIOS to get stuff from APIs, using the code above works once however when trying to use it again, it throws an error.
Cannot redeclare block-scoped variable 'data'
Trying to change data to anything else also doesn't work.
Example of what I'm trying to do with placeholder names.
let api1 = "INSERTAPILINKHERE";
if (args.length) {
api1 += `/++${args[0]}`;
}
const { data } = await axios.get(api1);
var variable1 = JSON.stringify(data);
variable1 = variable1.replace(/\D/g, "");
let api2 = "ANOTHERDIFFERENTAPILINK";
if (args.length) {
api2 += `/++${args[0]}`;
}
const { data2 } = await axios.get(api2);
const parsedJSON = JSON.parse(data2);
var valueFromJSON = parsedJSON.somevalue;
The syntax of const { data } = await axios.get(…) is called destructing and is equivalent to: const data = (await axios.get(…)).data.
It a shortcut take a specific field from an object. So writing this line twice is the same as defining two consts with the same name.
The solutions are:
Rename the variable const { data: newName } = …
Avoid using destructing and use the long way as I wrote above
I'm trying to replicate the code in this article:
https://depth-first.com/articles/2020/08/24/smiles-validation-in-the-browser/
What I'm trying to do different is that I'm using a textarea instead of input to take multi-line input. In addition to displaying an error message, I also want to display the entry which doesn't pass the validation.
The original validation script is this:
const path = '/target/wasm32-unknown-unknown/release/smival.wasm';
const read_smiles = instance => {
return smiles => {
const encoder = new TextEncoder();
const encoded = encoder.encode(`${smiles}\0`);
const length = encoded.length;
const pString = instance.exports.alloc(length);
const view = new Uint8Array(
instance.exports.memory.buffer, pString, length
);
view.set(encoded);
return instance.exports.read_smiles(pString);
};
};
const watch = instance => {
const read = read_smiles(instance);
document.querySelector('input').addEventListener('input', e => {
const { target } = e;
if (read(target.value) === 0) {
target.classList.remove('invalid');
} else {
target.classList.add('invalid');
}
});
}
(async () => {
const response = await fetch(path);
const bytes = await response.arrayBuffer();
const wasm = await WebAssembly.instantiate(bytes, { });
watch(wasm.instance);
})();
For working with a textarea, I've changed the watch function to this and added a <p id="indicator"> element to the html to display an error:
const watch = instance => {
const read = read_smiles(instance);
document.querySelector("textarea").addEventListener('input', e => {
const { target } = e;
var lines_array = target.value.split('/n');
var p = document.getElementById("indicator");
p.style.display = "block";
p.innerHTML = "The size of the input is : " + lines_array.length;
if (read(target.value) === 0) {
target.classList.remove('invalid');
} else {
target.classList.add('invalid');
}
});
}
I'm not even able to get a count of entries that fail the validation. I believe this is async js and I'm just a beginner in JavaScript so it's hard to follow what is happening here, especially the part where the function e is referencing itself.
document.querySelector("textarea").addEventListener('input', e => {
const { target } = e;
Can someone please help me in understanding this complicated code and figuring out how to get a count of entries that fail the validation and also printing the string/index of the same for helping the user?
There is a mistake in you code to count entries in the textarea:
var lines_array = target.value.split('\n'); // replace /n with \n
You are asking about the function e is referencing itself:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. You can find more informations Mdn web docs - Destructuring object
Looking for some help on porting this objective-c class method to JS/nativescript.. every variation I've tried has resulted in a TypeError: undefined is not a function...
https://developer.apple.com/documentation/avfoundation/avvideocomposition/1389556-init
Which I've tried to write in JS as:
const videoComp = AVVideoComposition.alloc().initWithAssetApplyingCIFiltersWithHandler(asset, (request) => { ... });
//OR
const videoComp = AVVideoComposition.alloc().initAssetApplyingCIFiltersWithHandler(asset, (request) => { ... });
//OR
const videoComp = AVVideoComposition.alloc().initAssetApplyingCIFiltersWithHandlerApplier(asset, (request) => { ... });
//OR
const videoComp = new AVVideoComposition(asset, (request) => { ... });
to name a few. essentially, I am trying to port this code to nativescript/JS:
let blurRadius = 6.0
let asset = AVAsset(url: streamURL)
let item = AVPlayerItem(asset: asset)
item.videoComposition= AVVideoComposition(asset: asset) { request in
let blurred = request.sourceImage.clampedToExtent().applyingGaussianBlur(sigma: blurRadius)
let output = blurred.clampedToRect(request.sourceImage.extent)
request.finish(with: output, context: nil)
}
found in this blog post: https://willowtreeapps.com/ideas/how-to-apply-a-filter-to-a-video-stream-in-ios
It should look something like this with JavaScript / Typescript,
let blurRadius = 6.0;
let asset = AVAsset.assetWithURL(streamURL);
let item = AVPlayerItem.alloc().initWithAsset(asset);
item.videoComposition = AVVideoComposition.videoCompositionWithAssetApplyingCIFiltersWithHandler(asset, request => {
let blurred = request.sourceImage.imageByClampingToExtent().imageByApplyingGaussianBlurWithSigma(blurRadius);
let output = blurred.imageByClampingToRect(request.sourceImage.extent);
request.finishWithImageContext(output, null);
});
Note: The code is untested and merely a translation of given native code. Make use of tns-platform-declarations for IntelliSense support.
I'm just starting to figure out React by putting together a bit of code from different parts, and from an online course.
I'm using React, Next and Axios to get an API from a cryptocurrency server.
The main issue I'm facing is:
I am able to console.log(coinObjects) under getInitialProps, and it displays the object correctly
Despite this, coinObjects does not get rendered in {this.props.coinObjects}
As a possible clue, linksArr does get rendered in {this.props.linksArr}
The code I have is as follows:
class MainIndex extends Component {
static async getInitialProps(props) {
// setup - empty array and list of coins
const coinList = ["NEO", "ETH", "BTC"];
const numCoins = coinList.length;
const coinObjects = [];
const linksArr = [];
const isServer = typeof window === "undefined";
// API GET
const baseUrl = "https://min-api.cryptocompare.com/data/histohour?";
for (let coinName of coinList) {
linksArr.push(
baseUrl.concat("fsym=", coinName, "&tsym=", "USD", "&limit=", "3")
);
}
const getObj = async linksArr => {
try {
let res = await axios.all(linksArr.map(l => axios.get(l)));
for (let i = 0; i < linksArr.length; i++) {
coinObjects[coinList[i]] = res[i].data.Data;
}
} catch (err) {
console.error(err);
}
};
await getObj(linksArr);
console.log(coinObjects);
// Return updated arrays
if (isServer) {
return { coinObjects, numCoins, linksArr };
} else {
return {};
}
}
render() {
return (
<Layout>
<h2>
CoinObject has {this.props.coinObjects.length} coins
// Returns 0
<br />
LinksArr has {this.props.linksArr.length} links
// Returns 3
</h2>
</Layout>
);
}
}
Could anyone please help me? I've exhausted all the Google searches, Stackoverflow posts and coding friends that I can find (just 1). I can't figure out what's wrong, and I hope that this isn't a silly question because I've been tweaking and changing things extensively, but have yet to figure out what's wrong.
Here the coinObject is set to an array:
const coinObjects = [];
But later is treated as an Object:
coinObjects[coinList[i]] = res[i].data.Data;
That means that you would want to add to the array like this:
for (let i = 0; i < linksArr.length; i++) {
let data = res[i].data.Data;
let name = coinList[i];
coinObjects.push({ name: name, data: data });
}
I'm trying to use Twilio Access Token on Firebase Functions with TypeScript.
export const returnToken = functions.https.onRequest((req, res) => {
const twilioAccessToken = twilio.jwt.AccessToken;
const envconf = functions.config();
const twilioAccountSid = envconf.twilio.sid; //saved them on environment
console.log(twilioAccountSid); //prints out fine
console.log(typeof twilioAccountSid !== "undefined"); //returns true
const twilioApiKey = envconf.twilio.apikey;
console.log(twilioApiKey); //prints fine too
const twilioApiSecret = envconf.twilio.apisecret;
console.log("gonna make a token"); //prints
const token = twilioAccessToken( //here it says TypeError: Cannot set property 'accountSid' of undefined
twilioAccountSid,
twilioApiKey,
twilioApiSecret
)
console.log("gonna make a grant");
const grant = new twilioAccessToken.VideoGrant();
token.addGrant(grant);
grant.room = "someroom";
token.identity = "someid";
res.send(token.toJwt());
})
and I get an error for the twilioAccessToken constructor which says
TypeError: Cannot set property 'accountSid' of undefined
Looking the source ->
function AccessToken(accountSid, keySid, secret, options) {
if (!accountSid) { throw new Error('accountSid is required'); }
if (!keySid) { throw new Error('keySid is required'); }
if (!secret) { throw new Error('secret is required'); }
options = options || {};
this.accountSid = accountSid;
AccessToken is a constructor, but your calling it like a regular function..
const token = twilioAccessToken(
You need to use new
const token = new twilioAccessToken(
Normal Javascript notation is if a function starts with a capital letter, it's a hint that it's a constructor. To keep with this standard I would say you want to also rename twilioAccessToken to TwilioAccessToken..