How can i make this reset button function work? - javascript

I am working on a very simple Weather API for practice and I just can't find a solution to make this resetFunc not be undefined / not a function.
I am loking for a way to make this function for the reset button not be undefined / not a function. I am attempting to make this reset function resetFunc() for the resetbtn only work after the displayExecuted flag becomes true, it keeps making the newText text node undefined.
I've tried with newText in both global and local scope.
let newText
let weatherDisplay;
let displayExecuted = false;
function getWeather() {
let resetbtn = document.getElementById(`resetbtn`)
let wbutton = document.getElementById(`wbutton`)
let weatherText = document.getElementById('w')
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const endpoint = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&hourly=temperature_2m&current_weather=true`
fetch(endpoint)
.then(res => res.json())
.then(data => {
console.log(data)
const weather = data['current_weather'].temperature
console.log(weather)
newText = document.createTextNode(`${weather}`)
weatherDisplay = function weatherDisplay() {
if (!displayExecuted) {
weatherText.querySelector('p').append(newText.nodeValue + " "+'degrees') }
displayExecuted = true
}
resetFunc = function resetFunc () {
if (displayExecuted === true) {
newText.nodeValue = " "
}
}
})
.catch(error => {
console.error("Error fetching data:", error)
})
.catch(error => {
console.error("Error fetching data", error)
})
})
wbutton.addEventListener(`click`,weatherDisplay,{once: true})
resetbtn.addEventListener(`click`,resetFunc)
} else {
console.error('Geolocation not supported in this browser')
}}
getWeather()
I've tried global variables and also tried formatting the functions in different scopes. I also want to add that I'm a beginner programmer, so please don't make fun of this code too much.

Related

Appending data from api into DOM

const url = `https://catfact.ninja/fact?max_length=140`;
const getFact = () => {
return fetch('https://catfact.ninja/fact?max_length=140')
.then(res => res.json())
}
const createFactDiv = (fact) => {
const factContainer = document.createElement('div')
const setup = document.createElement('p')
setup.innerText = fact.fact
factContainer.append(setup)
return factContainer
}
const appendFact = (factDiv) => {
const factContainer = document.getElementById('factContainer')
factContainer.append(FactDiv)
}
document.addEventListener('DOMContentLoaded', () => {
})
getFact().then ((fact) => {
const FactDiv = createFactDiv(fact)
append.fact (FactDiv)
})
I have tried several things, fairly new to JS and it is tricky. I am trying to create an app that displays cat facts. I was seeing the DIV with the FACT inside correctly in the console.log in the elements of the DOM, but now I don't see it and I keep seeing
Uncaught (in promise) ReferenceError: append is not defined
Any idea what to do? Much appreciated !
Yep, it's our old friend spelling errors! Here is some working code:
const url = `https://catfact.ninja/fact?max_length=140`;
const getFact = () => {
return fetch('https://catfact.ninja/fact?max_length=140')
.then(res => res.json())
}
const createFactDiv = (fact) => {
const factContainer = document.createElement('div');
const setup = document.createElement('p');
setup.innerText = fact.fact;
factContainer.append(setup);
return factContainer
}
const appendFact = (factDiv) => {
const factContainer = document.getElementById('factContainer');
factContainer.append(factDiv);
}
//This is unused
/*
document.addEventListener('DOMContentLoaded', () => {
})
*/
getFact().then ((fact) => {
const factDiv = createFactDiv(fact);
appendFact(factDiv);
})
This is why it's important to consistently use camelCase:
In appendFact() you took a factDiv parameter but then tried to use FactDiv, which doesn't exist in that function
As noted by Robin, you typed append.fact(FactDiv) instead of appendFact(FactDiv)
This should be refactored to appendFact(factDiv) to stick with camelCase.
Also watch your spacing, and I like to have semicolons at the end of my lines also!

Autofill state and city based on zip code input using Sepomex API

I am trying to autofill city and state fields based on zip code input using sepomex API (for Mexico), on a site in corvid by wix, which is based on javascript but I think there is something wrong in the line json.response[0]["ciudad"].
$w.onReady(function () {
$w("#input1").onInput(() =>{
let zipcode = $w("#input1").value;
$w("#input2").value = "";
$w("#input3").value = "";
if (zipcode.length === 5) {
let apiUrl = "";
apiUrl = "https://api-sepomex.hckdrk.mx/query/info_cp/";
fetch(apiUrl + zipcode, {method: 'get'})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
else{
return Promise.reject("fetch was not successful")
}
})
.then((json) => {
console.log(json);
let response = json.response;
$w("#input10").value = json.response[0]["ciudad"];
$w("#input11").value = json.response[0]["estado"];
$w("#text148").collapse();
})
.catch(() =>{
$w("#text148").expand()
})
}
})
I can't display any data
There is the output on API
[
{
"error": false,
"code_error": 0,
"error_message": null,
"response": {
"cp": "44110",
"asentamiento": "Vallarta Poniente",
"tipo_asentamiento": "Fraccionamiento",
"municipio": "Guadalajara",
"estado": "Jalisco",
"ciudad": "Guadalajara",
"pais": "México"
}
}
]
change code inside second promise to.
.then((json) => {
let response = json[0].response;
$w("#input10").value = response.ciudad;
$w("#input11").value = response.estado;
$w("#text148").collapse();
})
now it should work
Solved
.then((json) =>{
let response = json[0].response;
$w("#input11").value = json[0].response["ciudad"];
$w("#input10").value = json[0].response["estado"];
$w("#text148").collapse();
})

(js) writing async function using a api wrapper

I'm currently using https://github.com/pixtron/bybit-api/tree/master
and what im trying to do looks like this:
const {RestClient} = require('#pxtrn/bybit-api');
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const client = new RestClient(API_KEY, PRIVATE_KEY);
client.getPosition({symbol: 'BTCUSD'})
.then(msg => {
let btcPositionCheck = msg.result.size;
if (btcPositionCheck == 0) {
console.log("empty")
} else {
let btcPositionSize = btcPositionCheck;
let btcPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
client.getPosition({symbol: 'ETHUSD'})
.then(msg => {
let ethPositionCheck = msg.result.size;
if (ethPositionCheck == 0) {
console.log("empty")
} else {
let ethPositionSize = ethPositionCheck;
let ethPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
console.log(btcPositionSize + ' ' + ethPositionSize)
returning me the following error:
ReferenceError: btcPositionSize is not defined
simply because im out of scope, I'm aware. however, I'm unsure how to approach rewriting the following to better allow me to construct what I need. (I need to call getPosition for the 3 different assets as well and take the variables from each call to use later in my code.) if that makes any sense. help would be greatly appreciated
edit:
async function getPosition({symbol: BTCUSD}) {
try {
let btcPositionCheck = msg.result.size;
} catch(error) {
return null;
}
}
im trying to rewrite it but im unsure how
Once you get into asynchronous context, you need to stay in asynchronous context to get values. In your case, there are promises to be resolved, you can await them and then print.
Also you need to make sure that your variables are in valid scope
const {RestClient} = require('#pxtrn/bybit-api');
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const client = new RestClient(API_KEY, PRIVATE_KEY);
async function doItAll() {
let btcPositionCheck;
let ethPositionCheck;
await client.getPosition({symbol: 'BTCUSD'})
.then(msg => {
btcPositionCheck = msg.result.size;
if (btcPositionCheck == 0) {
console.log("empty")
} else {
let btcPositionSize = btcPositionCheck;
let btcPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
await client.getPosition({symbol: 'ETHUSD'})
.then(msg => {
ethPositionCheck = msg.result.size;
if (ethPositionCheck == 0) {
console.log("empty")
} else {
let ethPositionSize = ethPositionCheck;
let ethPositionSide = msg.result.side;
}
})
.catch(err => {
console.error(err);
});
console.log(btcPositionSize + ' ' + ethPositionSize)
}
Note that nicer way is to await promises into value, which means it can look like that (to use await, it needs to be in an async function)
const msg = await client.getPosition({symbol: 'BTCUSD'})
btcPositionCheck = msg.result.size;
if (btcPositionCheck == 0) {
console.log("empty")
} else {
let btcPositionSize = btcPositionCheck;
let btcPositionSide = msg.result.side;
}

TypeError: Cannot read property 'json' of undefined google assistant

I'm working on a Bus Stop google assistant script in node.js
I based it on the weather API example by Google. Given the right API key, the weather function will work and return the weather for a place on a date.
The Bus Stop API will return the correct output in the console.log, but the output does not get passed on to the else if statement where the function is called.
I get 2 errors:
"Unhandled rejection" Which can be alleviated by commenting out the reject code in the callBusApi.
"TypeError: Cannot read property 'json' of undefined
at callBusApi.then.catch (/user_code/index.js:45:9)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)" This is where it breaks. I think because it doesn't get the output from the function.
My script looks as follows:
'use strict';
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = 'enter a working key';
exports.weatherWebhook = (req, res, re) => {
if(req.body.queryResult.intent['displayName'] == 'weather'){
// Get the city and date from the request
let city = req.body.queryResult.parameters['geo-city']; // city is a required param
// Get the date for the weather forecast (if present)
let date = '';
if (req.body.queryResult.parameters['date']) {
date = req.body.queryResult.parameters['date'];
console.log('Date: ' + date);
}
// Call the weather API
callWeatherApi(city, date).then((output) => {
res.json({ 'fulfillmentText': output }); // Return the results of the weather API to Dialogflow
}).catch(() => {
res.json({ 'fulfillmentText': `I don't know the weather but I hope it's good!` });
});
}
else if (req.body.queryResult.intent['displayName'] == 'mytestintent'){
callBusApi().then((output) => {
re.json({ 'fulfillmentText': output }); // Return the results of the bus stop API to Dialogflow
}).catch(() => {
re.json({ 'fulfillmentText': `I do not know when the bus goes.` });
});
}
};
function callBusApi () {
return new Promise((resolve, reject) => {
http.get({host: 'v0.ovapi.nl', path: '/stopareacode/beunav/departures/'}, (re) => {
let boy = '';
re.on('data', (d) => {boy+=d});
re.on('end',() => {
let response = JSON.parse(boy)
var firstKey = Object.keys(response['beunav']['61120250']['Passes'])[0];
var timeKey = Object.keys(response['beunav']['61120250']['Passes'][firstKey])[19];
var destKey = Object.keys(response['beunav']['61120250']['Passes'][firstKey])[1];
let destination = response['beunav']['61120250']['Passes'][firstKey][destKey];
let datetime = response['beunav']['61120250']['Passes'][firstKey][timeKey];
let fields = datetime.split('T');
let time = fields[1];
let output = `Next bus to ${destination} departs at ${time} .`;
console.log(output)
resolve(output);
});
re.on('error', (error) => {
console.log(`Error talking to the busstop: ${error}`)
reject();
});
});
});
};
function callWeatherApi (city, date) {
return new Promise((resolve, reject) => {
let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' +
'&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date;
console.log('API Request: ' + host + path);
http.get({host: host, path: path}, (res) => {
let body = '';
res.on('data', (d) => { body += d; });
res.on('end', () => {
let response = JSON.parse(body);
let forecast = response['data']['weather'][0];
let location = response['data']['request'][0];
let conditions = response['data']['current_condition'][0];
let currentConditions = conditions['weatherDesc'][0]['value'];
let output = `Current conditions in the ${location['type']}
${location['query']} are ${currentConditions} with a projected high of
${forecast['maxtempC']}°C or ${forecast['maxtempF']}°F and a low of
${forecast['mintempC']}°C or ${forecast['mintempF']}°F on
${forecast['date']}.`;
console.log(output);
resolve(output);
});
res.on('error', (error) => {
console.log(`Error calling the weather API: ${error}`)
reject();
});
});
});
}
It appears that your method has a parameter too much
exports.weatherWebhook = (req, res, re) => {
should be:
exports.weatherWebhook = (req, res) => {
And as well on the variable 're' used in the handling of the 'mytestintent' inside the webhook.
This explains the 'not defined' error when trying to set a json value on it.
Regarding your 2 question: It usually comes when the value of the variable is not defined.
First check wheather you have defined the JSON variable in your .js file.
Or its in some other format.

ReactJS onClick function is not triggering correctly

Function is ONLY triggering correctly if I add e.preventDefault(). However, I want it to push the user to '/' after the user submits the form. Here is the function I am trying to trigger:
onAddPoints = (e) => {
e.preventDefault();
//history.push('/');
let { phoneNumber, points, onPointsChange } = this.state;
//convert string to int -> calculate update points
let p1 = Number(points);
let p2 = Number(onPointsChange);
const updatedPoints = p1 + p2;
//update points
firebase.auth().onAuthStateChanged((user) => {
if(user) {
const docRef = database.collection('users').doc(user.uid).collection('customers').doc(phoneNumber);
docRef.update({
"points": updatedPoints
}).then(() => {
console.log('success');
}).catch((error) => {
console.log(error);
})
} else {
window.location.href = '/';
}
});
}
You need to wait to see the result of your request.
If the request is right then is ok if you send the user to another page but if the request gets an error then you have to tell the user that something is wrong.
firebase.auth().onAuthStateChanged((user) => {
if(user) {
const docRef = database.collection('users').doc(user.uid).collection('customers').doc(phoneNumber);
docRef.update({
"points": updatedPoints
}).then(() => {
history.push('/');
console.log('success');
}).catch((error) => {
console.log(error);
})
} else {
window.location.href = '/';
}
});
And is ok if you use e.preventDefeault() because it stops the default form action flow onSubmit which is go to the page that is setup in the action='./update.php' property. That's commonly used in php apps for example by doing that you send all the inputs info to that update.php.

Categories

Resources