Async await on rendering component react - javascript

the js code below performs the loading of a series of fields remotely and then displays them on a map, the problem is that it calls it does not wait for the await and I proceed so the data is not displayed on the map which is redirected by the component , how can I do to make the chaima wait for the response of the function before proceeding to render the map
import {getmarcaturegiornaliere} from "module.js";
MyComponent.js
class Am4chartMap extends Component {
async componentDidMount() {
let map = am4core.create("map", am4maps.MapChart);
//Load values from response this function->
var marcature=await getmarcaturegiornaliere();
map.geodata = am4geodata_usaHigh;
map.percentHeight = 90;
map.dy = 10;
let polygonSeries = map.series.push(new am4maps.MapPolygonSeries());
polygonSeries.useGeodata = true;
map.homeZoomLevel = 1.2;
map.zoomControl = new am4maps.ZoomControl();
map.zoomControl.layout = 'horizontal';
map.zoomControl.align = 'left';
map.zoomControl.valign = 'bottom';
map.zoomControl.dy = -10;
map.zoomControl.contentHeight = 20;
map.zoomControl.minusButton.background.fill = am4core.color("#C7D0FF");
map.zoomControl.minusButton.background.stroke = am4core.color("#6979C9");
map.zoomControl.minusButton.label.fontWeight = 600;
map.zoomControl.minusButton.label.fontSize = 22;
map.zoomControl.minusButton.scale = .75;
map.zoomControl.minusButton.label.scale = .75;
map.zoomControl.plusButton.background.fill = am4core.color("#C7D0FF");
map.zoomControl.plusButton.background.stroke = am4core.color("#6979C9");
map.zoomControl.plusButton.label.fontWeight = 600;
map.zoomControl.plusButton.label.fontSize = 22;
map.zoomControl.plusButton.label.align = "center";
map.zoomControl.plusButton.scale = .75;
map.zoomControl.plusButton.label.scale = .75;
map.zoomControl.plusButton.dx = 5;
let plusButtonHoverState = map.zoomControl.plusButton.background.states.create("hover");
plusButtonHoverState.properties.fill = am4core.color("#354D84");
let minusButtonHoverState = map.zoomControl.minusButton.background.states.create("hover");
minusButtonHoverState.properties.fill = am4core.color("#354D84");
let polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#474D84");
polygonTemplate.stroke = am4core.color("#6979C9")
let hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#354D84");
let citySeries = map.series.push(new am4maps.MapImageSeries());
citySeries.data = marcature;
citySeries.dataFields.value = "size";
let city = citySeries.mapImages.template;
city.nonScaling = true;
city.propertyFields.latitude = "latitude";
city.propertyFields.longitude = "longitude";
let circle = city.createChild(am4core.Circle);
circle.fill = am4core.color("#C7D0FF");
circle.strokeWidth = 0;
let circleHoverState = circle.states.create("hover");
circleHoverState.properties.strokeWidth = 1;
circle.tooltipText = '{tooltip}';
circle.propertyFields.radius = 'size';
this.map = map;
}
componentWillUnmount() {
if(this.map) {
this.map.dispose();
}
}
render() {,.
module.js
//Setup server
import server from "./settings";
//Rest call axios module
const axios = require('axios').default;
export function getmarcaturegiornaliere() {
var date="03-02-2021";
console.log("Data: "+date);
var listmarcature=[];
axios.post(server.url+'/Utente/CaricamentoStoricoGiornonaliero', {
Data: date,
IdUtente: '3',
CalcoloOreGiornaliere: true
})
.then(function (response) {
console.log("Response: "+response.data);
//Vado ad iterare la response
let data = response.data;
for (let index in data){
console.log("Stato: "+data[index].Longitudine);
var datatemp={
"latitude" : data[index].Latitudine,
"longitude" : data[index].Longitudine,
"size" : 5,
"tooltip" : data[index].Stato,
};
listmarcature.push(datatemp);
}
}).catch(function (error) {
console.log("Errore: "+error);
});
return listmarcature;
}

Your function getmarcaturegiornaliere is not async, and this is the problem.
It will always return you an empty array [], because the return listmarcature; is executed before the .then() is. Therefore you return an empty array, and somewhere in the future the .then() will happen (and it will do nothing because you already returned).
The solution would be: Make it async.
There are some syntaxes available for that, I will bring you the best for this case:
Put async in the funciton: export async function getmarcaturegiornaliere() {
Add await before the axios call: await axios.post(...)

Related

I want to find Biggest Changerate in the prices of coins

i want to find biggests changerate in the prices in my coins data
like if SDT oldprice is 1.00 and
new price is 1.02 = 2%
and if it was the biggests changerate in the coins my script should printing it
but the script dont working
it only keep give me same coin
const math = require('mathjs');
const fetch = require('node-fetch');
get()
async function get() {
const response = await fetch("https://trade.kucoin.com/_api/currency/prices?base=USD&targets=&lang=en_US");
const coin1 = await response.json();
const olddata = coin1.data
const tokens = Object.keys(olddata)
const oldprice = Object.values(olddata)
get1()
async function get1() {
const response = await fetch("https://trade.kucoin.com/_api/currency/prices?base=USD&targets=&lang=en_US");
const coin2 = await response.json();
const newdata = coin2.data
const tokens = Object.keys(newdata)
const newprice = Object.values(newdata)
function findLargestDifference() {
var large = null;
var index = 0;
for (var i = 0; i < oldprice.length; i++) {
var change = tokens[i].newprice / oldprice[i].oldprice;
if (change > large) {
large = change;
index = i;
}
}
console.log(tokens[index])
return tokens[index];
}
findLargestDifference()
}
}
here how data looks https://prnt.sc/19syjjg

Updating the query data in cloud firestore nested map fields

I'm trying to update the data in nested map fields in firestore, my form is a window form that has 4 sides (wSide1,wSide2,wSide3,wSide4), what my form is doing is if customer select 1 field which is wSide1 and it needs to be updated then only this field only be updated but in my case it is updating all 4 sides, the one which is selected for example side 1 only that has the correct updated values other 3 sides updates with the false values. as my form is dynamic it only shows the field which is selected.
I only want to update the field which is selected, all other has to be null.
js & firestore query
function updateWindowForm(form, type){
var name = $('#name_'+type).val();
var type = $('#type_'+type).val();
const taskformWindow = document.getElementById("taskformWindow");
let editStatus = false;
let id = '';
const updateTask = (id, updatedTask) => db.collection('Buildings').doc(buildingID).collection('rooms').doc(roomID).collection('objects').doc(objectID).update(updatedTask);
window.addEventListener("DOMContentLoaded", async (e) => {
id = doc.id;
editStatus = true;
btnsEdit.forEach((btn) => {
btn.addEventListener("click", async (e) => {
try {
const doc = await getTask(e.target.dataset.id);
const task = doc.data();
editStatus = true;
id = doc.id;
taskformWindow["btn-update-data"].innerText = "Update";
} catch (error) {
console.log(error);
}
});
});
});
taskformWindow.addEventListener("click", async (e) => {
e.preventDefault();
var name_Window = document.getElementById('name_Window').value;
var wAluminium = document.getElementById('wAluminium').checked;
var wColorMeasurement = document.getElementById('wColorMeasurement').value;
var wComments = document.getElementById('wComments').value;
var wForEnd1 = document.getElementById('wForEnd1').checked;
var wForEnd2 = document.getElementById('wForEnd2').checked;
var wSideOfWindows = document.getElementById('wSideOfWindows').value;
var wHardwareManufacturer = document.getElementById('wHardwareManufacturer').value;
var wPlastic = document.getElementById('wPlastic').checked;
//Side 1
var wAxis1_1 = document.getElementById('wAxis1_1').checked;
var wAxis1_2 = document.getElementById('wAxis1_2').checked;
var wBackSet1 = document.getElementById('wBackSet1').value;
var wDirectionLR1_1 = document.getElementById('wDirectionLR1_1').checked;
var wDirectionLR1_2 = document.getElementById('wDirectionLR1_2').checked;
var wHandleHeight1 = document.getElementById('wHandleHeight1').value;
var wOverlapWidth1 = document.getElementById('wOverlapWidth1').value;
var wSashRebateHeight1 = document.getElementById('wSashRebateHeight1').value;
var wSashRebateWidth1 = document.getElementById('wSashRebateWidth1').value;
//Side 2
var wAxis2_1 = document.getElementById('wAxis2_1').checked;
var wAxis2_2 = document.getElementById('wAxis2_2').checked;
var wBackSet2 = document.getElementById('wBackSet2').value;
var wDirectionLR2_1 = document.getElementById('wDirectionLR2_1').checked;
var wDirectionLR2_2 = document.getElementById('wDirectionLR2_2').checked;
var wHandleHeight2 = document.getElementById('wHandleHeight2').value;
var wOverlapWidth2 = document.getElementById('wOverlapWidth2').value;
var wSashRebateHeight2 = document.getElementById('wSashRebateHeight2').value;
var wSashRebateWidth2 = document.getElementById('wSashRebateWidth2').value;
//Side 3
var wAxis3_1 = document.getElementById('wAxis3_1').checked;
var wAxis3_2 = document.getElementById('wAxis3_2').checked;
var wBackSet3 = document.getElementById('wBackSet3').value;
var wDirectionLR3_1 = document.getElementById('wDirectionLR3_1').checked;
var wDirectionLR3_2 = document.getElementById('wDirectionLR3_2').checked;
var wHandleHeight3 = document.getElementById('wHandleHeight3').value;
var wOverlapWidth3 = document.getElementById('wOverlapWidth3').value;
var wSashRebateHeight3 = document.getElementById('wSashRebateHeight3').value;
var wSashRebateWidth3 = document.getElementById('wSashRebateWidth3').value;
//Side 4
var wAxis4_1 = document.getElementById('wAxis4_1').checked;
var wAxis4_2 = document.getElementById('wAxis4_2').checked;
var wBackSet4 = document.getElementById('wBackSet4').value;
var wDirectionLR4_1 = document.getElementById('wDirectionLR4_1').checked;
var wDirectionLR4_2 = document.getElementById('wDirectionLR4_2').checked;
var wHandleHeight4 = document.getElementById('wHandleHeight4').value;
var wOverlapWidth4 = document.getElementById('wOverlapWidth4').value;
var wSashRebateHeight4 = document.getElementById('wSashRebateHeight4').value;
var wSashRebateWidth4 = document.getElementById('wSashRebateWidth4').value;
try {
if (!editStatus) {
await updateTask(id, {
name:name_Window,
Form:{
wAluminium: wAluminium,
wColorMeasurement: wColorMeasurement,
wComments: wComments,
wForEnd1: wForEnd1,
wForEnd2: wForEnd2,
wHardwareManufacturer: wHardwareManufacturer,
wPlastic: wPlastic,
wSide1:{
wAxis1_1: wAxis1_1,
wAxis1_2: wAxis1_2,
wBackSet1: wBackSet1,
wDirectionLR1_1: wDirectionLR1_1,
wDirectionLR1_2: wDirectionLR1_2,
wHandleHeight1: wHandleHeight1,
wOverlapWidth1: wOverlapWidth1,
wSashRebateHeight1: wSashRebateHeight1,
wSashRebateWidth1: wSashRebateWidth1,
},
wSide2:{
wAxis2_1: wAxis2_1,
wAxis2_2: wAxis2_2,
wBackSet1: wBackSet2,
wDirectionLR2_1: wDirectionLR2_1,
wDirectionLR2_2: wDirectionLR2_2,
wHandleHeight2: wHandleHeight2,
wOverlapWidth2: wOverlapWidth2,
wSashRebateHeight2: wSashRebateHeight2,
wSashRebateWidth2: wSashRebateWidth2,
},
wSide3:{
wAxis3_1: wAxis3_1,
wAxis3_2: wAxis3_2,
wBackSet1: wBackSet3,
wDirectionLR3_1: wDirectionLR3_1,
wDirectionLR3_2: wDirectionLR3_2,
wHandleHeight3: wHandleHeight3,
wOverlapWidth3: wOverlapWidth3,
wSashRebateHeight3: wSashRebateHeight3,
wSashRebateWidth3: wSashRebateWidth3,
},
wSide4:{
wAxis4_1: wAxis4_1,
wAxis4_2: wAxis4_2,
wBackSet4: wBackSet4,
wDirectionLR4_1: wDirectionLR4_1,
wDirectionLR4_2: wDirectionLR4_2,
wHandleHeight4: wHandleHeight4,
wOverlapWidth4: wOverlapWidth4,
wSashRebateHeight4: wSashRebateHeight4,
wSashRebateWidth4: wSashRebateWidth4,
},
wSideOfWindows: wSideOfWindows,
}
})
editStatus = false;
id = '';
taskformWindow['btn-update-window-data'].innerText = 'Daten aktualisiert';
swal("", "Daten wurden aktualisert!", "success");
}
taskformWindow.reset();
} catch (error) {
console.log(error);
}
});
}
I can't see the code you use for updating your data but I can ausme that you probably did not set the merge to true while saving the data.
Take a look at this code snipped:
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
By setting that we ensure to udate only the fields we want to and leave the rest as it is. Still make sure not to send fields with a null value because that is a valid value for firestore and it doesn't mean that those fields will by skipped in the update process. You can find more about it here.

Javascript get method and airtable

Hye i am having a little trouble again i am supposed to put a list of questions in airtable and then print them to my screen but i am working with a fetch reqeust en then e method of get but i have the feeling like my empty variable aren't being filled with my questions
its in javascript btw :
here's my code :
; (function (){
window.addEventListener('load', function(){
document.getElementById('next').addEventListener('click', function(){
window.location.href = 'vragenlijst2.html';
})
let vrg1 = document.getElementById('1vraag');
let vrg2 =document.getElementById('2vraag');
let vrg3 = document.getElementById('3vraag');
let vrg4 = document.getElementById('4vraag');
let vrg5 = document.getElementById('5vraag');
let vrg6 = document.getElementById('6vraag');
let vrg7 = document.getElementById('7vraag');
let vrg8 = document.getElementById('8vraag');
let vrg9 = document.getElementById('9vraag');
let vrg10 = document.getElementById('10vraag');
let Vragenlijst_id = 1;
let getData = function(){
fetch('https://api.airtable.com/v0/appojP2iMG4i3P61S/EDBL', {
method: 'GET',
headers: {
'Authorization' : 'Bearer keyDhD8sLGjcEuA4K'
}
})
.then(Response => Response.json())
.then(JSON => {
console.log(JSON)
for(let index = 0; index < JSON.records.length; index++){
let Qstn = JSON.records[index];
if(Vragenlijst_id === Qstn.fields.vragenlijst){
let vrg1_db = Qstn.fields.Vraag1;
let vrg2_db = Qstn.fields.Vraag2;
let vrg3_db = Qstn.fields.Vraag3;
let vrg4_db = Qstn.fields.Vraag4;
let vrg5_db = Qstn.fields.Vraag5;
let vrg6_db = Qstn.fields.Vraag6;
let vrg7_db = Qstn.fields.Vraag7;
let vrg8_db = Qstn.fields.Vraag8;
let vrg9_db = Qstn.fields.Vraag9;
let vrg10_db = Qstn.fields.Vraag10;
vrg1 = vrg1_db;
vrg2 = vrg2_db;
vrg3 = vrg3_db;
vrg4 = vrg4_db;
vrg5 = vrg5_db;
vrg6 = vrg6_db;
vrg7 = vrg7_db;
vrg8 = vrg8_db;
vrg9 = vrg9_db
vrg10 = vrg10_db;
console.log(vrg1);
}
}
})
}
getData();
function create (){
let par = document.createElement('p');
par.innerHTML = vrg1;
document.getElementById('1vraag').appendChild(par);
}
document.getElementById('1vraag').innerHTML = create()

How to handle axios.all request fails

How can I handle request fails in this example of axios.all requests. I.e. if all servers are responde with JSON all is okay and I have JSON file at end of a cycle. But if one of this servers not responde with JSON or not responde at all I do have nothing in "/data.json" file, even all other servers are working perfectly. How can I catch a server fail and skip it?
var fs = require("fs");
var axios = require('axios');
var util = require('util');
var round = 0;
var tmp = {};
var streem = fs.createWriteStream(__dirname + '/data.json', {flags : 'w'});
toFile = function(d) { //
streem.write(util.format(d));
};
start();
setInterval(start, 27000);
function start(){
streem = fs.createWriteStream(__dirname + '/data.json', {flags : 'w'});
monitor();
}
function monitor(){
axios.all([
axios.get('server1:api'),
axios.get('server2:api'),
axios.get('server3:api'),
axios.get('server4:api'),
]).then(axios.spread((response1, response2, response3, response4) => {
tmp.servers = {};
tmp.servers.server1 = {};
tmp.servers.server1 = response1.data;
tmp.servers.server2 = {};
tmp.servers.server2 = response2.data;
tmp.servers.server3 = {};
tmp.servers.server3 = response3.data;
tmp.servers.server4 = {};
tmp.servers.server4 = response4.data;
toFile(JSON.stringify(tmp));
round++;
streem.end();
streem.on('finish', () => {
console.error('Round: ' + round);
});
})).catch(error => {
console.log(error);
});
}
The most standard way to approach this would be a recursive function like below.
let promises = [
axios.get('server1:api'),
axios.get('server2:api'),
axios.get('server3:api'),
axios.get('server4:api'),
];
async function monitor() {
const responses = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments))[0];
const nextPromise = promises.shift();
if (nextPromise) {
try {
const response = await getSentenceFragment(offset);
responses.push(response);
}
catch (error) {
responses.push({});
}
return responses.concat(await monitor(responses));
} else {
return responses;
}
}
monitor([]).then(([response1, response2, response3, response4]) => {
tmp.servers = {};
tmp.servers.server1 = {};
tmp.servers.server1 = response1.data;
tmp.servers.server2 = {};
tmp.servers.server2 = response2.data;
tmp.servers.server3 = {};
tmp.servers.server3 = response3.data;
tmp.servers.server4 = {};
tmp.servers.server4 = response4.data;
toFile(JSON.stringify(tmp));
round++;
streem.end();
streem.on('finish', () => {
console.error('Round: ' + round);
});
});

I would like to analyze the image with tensorflw.js - nodejs

mobilenet.js
var loadFrozenModel = require('#tensorflow/tfjs-converter');
var NamedTensorMap = require('#tensorflow/tfjs-converter');
var tfc = require('#tensorflow/tfjs-core');
var IMAGENET_CLASSES = require('./imagenet_classes');
const GOOGLE_CLOUD_STORAGE_DIR = 'https://storage.googleapis.com/tfjs-models/savedmodel/';
const MODEL_FILE_URL = 'mobilenet_v1_1.0_224/optimized_model.pb';
const WEIGHT_MANIFEST_FILE_URL = 'mobilenet_v1_1.0_224/weights_manifest.json';
const INPUT_NODE_NAME = 'input';
const OUTPUT_NODE_NAME = 'MobilenetV1/Predictions/Reshape_1';
const PREPROCESS_DIVISOR = tfc.scalar(255 / 2);
class MobileNet {
constructor() {}
async load() {
this.model = await loadFrozenModel(
GOOGLE_CLOUD_STORAGE_DIR + MODEL_FILE_URL,
GOOGLE_CLOUD_STORAGE_DIR + WEIGHT_MANIFEST_FILE_URL);
}
dispose() {
if (this.model) {
this.model.dispose();
}
}
predict(input) {
const preprocessedInput = tfc.div(
tfc.sub(input.asType('float32'), PREPROCESS_DIVISOR),
PREPROCESS_DIVISOR);
const reshapedInput =
preprocessedInput.reshape([1, ...preprocessedInput.shape]);
const dict = {};
dict[INPUT_NODE_NAME] = reshapedInput;
return this.model.execute(dict, OUTPUT_NODE_NAME);
}
getTopKClasses(predictions, topK) {
const values = predictions.dataSync();
predictions.dispose();
let predictionList = [];
for (let i = 0; i < values.length; i++) {
predictionList.push({value: values[i], index: i});
}
predictionList = predictionList
.sort((a, b) => {
return b.value - a.value;
})
.slice(0, topK);
return predictionList.map(x => {
return {label: IMAGENET_CLASSES[x.index], value: x.value};
});
}
}
module.exports = MobileNet;
test.js
var tfc = require('#tensorflow/tfjs-core');
var MobileNet = require('./mobilenet');
var fs = require('fs');
var image = require('get-image-data')
var i = 0;
var meta;
image('./cat.jpg', function(err, getImageData){
if(err) throw err;
console.log('start to image data ');
console.log(i++);
console.log("meta : " + getImageData.data.length);
console.log("getImageData :"+getImageData);
const mobileNet = new MobileNet();
console.time('Loading of model');
// await mobileNet.load();
console.timeEnd('Loading of model');
console.log("maybee this is error on the data type");
const pixels = tfc.fromPixels(image);
console.time('First prediction');
let result = mobileNet.predict(pixels);
const topK = mobileNet.getTopKClasses(result, 5);
console.timeEnd('First prediction');
resultElement.innerText = '';
topK.forEach(x => {
resultElement.innerText += `${x.value.toFixed(3)}: ${x.label}\n`;
});
console.time('Subsequent predictions');
result = mobileNet.predict(pixels);
mobileNet.getTopKClasses(result, 5);
console.timeEnd('Subsequent predictions');
mobileNet.dispose();
});
I want to analyze the image using the tensorflow.js.
But it doesn't work.
ReferenceError: ImageData is not defined
at MathBackendCPU.fromPixels (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/kernels/backend_cpu.js:75:31)
at Engine.fromPixels (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/engine.js:292:29)
at ArrayOps.fromPixels (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/ops/array_ops.js:195:41)
at /Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/ops/operation.js:11:61
at Object.Tracking.tidy (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/tracking.js:36:22)
at Object.descriptor.value [as fromPixels] (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/ops/operation.js:11:26)
at /Users/leeyongmin/Documents/tfjs-converter-master-2/demo/test.js:26:22
at /Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/get-image-data/index.js:18:7
at load (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/get-image/server.js:18:5)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)

Categories

Resources