for loop only iterating twice with axios - react-native

const [Datalist,setDatalist] = useState([]);
useEffect(() => {
axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
.then(response => {
const questions = response.data;
const datalist = [];
for (let i = 0; i < questions.length - 1; i++) {
const data = new Object();
data.isExpanded = false;
data.question_id = questions[i].id;
data.question = questions[i].content;
data.type = questions[i].type;
data.commentType = questions[i].comment_type;
data.answer = [];
datalist.push(data);
}
setDatalist(datalist);
});
},[]);
I have three questions in my database currently. The for loop should be iterating through 0 to 2, however, it is only iterating twice.
And I'm also having problems putting the data into Datalist.
Anybody know where the issue is??
Thanks in advance!!

Change your for loop to this:
for (let i = 0; i < questions.length; i++)

Since you are iterating over each question you receive, you could use the map-method (if your environment supports ES6-Syntax - but since you're using react, it most likely dooes).
From the MDN Docs:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
With map, your code could look like this:
(Also note the removal of const data = new Object();. you can initialize an object and assign its properties/values at the same time)
const [Datalist,setDatalist] = useState([]);
useEffect(() => {
axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
.then(response => {
const questions = response.data;
const datalist = questions.map(question => {
return {
isExpanded: false;
question_id: question.id;
question: question.content;
type: question.type;
commentType: question.comment_type;
answer: [];
};
});
setDatalist(datalist);
});
},[]);

Related

React Native map "Undefined" is not a function

I'm trying to get data from API
but. I'm getting this error Error Image.
Here is my code.
const [datas, setDatas] = useState(" ");
const res = async () => {
const response = await axios.get("http://hasanadiguzel.com.tr/api/kurgetir");
setDatas(response.data.TCMB_AnlikKurBilgileri);
};
datas.map((item) => {
return (
<KurCard
title={item.Isim}
alis={item.BanknoteBuying}
satis={item.BanknoteSelling}
/>
);
});
How can I solve this?
I'm trying to map() datas, because I need it
Hi #n00b,
The data that datas is initially being set to an empty string, which does not have a map method. First, you need an empty array instead of an empty stringuseState([]). Now you can map.
const [datas, setDatas] = useState([]);
const res = async () => {
const response = await axios.get('http://hasanadiguzel.com.tr/api/kurgetir');
setDatas(response.data.TCMB_AnlikKurBilgileri);
};
{datas.length > 0 &&
datas.map((item) => {
return <KurCard title={item.Isim} alis={item.BanknoteBuying} satis={item.BanknoteSelling}/>
})
}
make sure you data. it has a length greater than 0 before trying to map over it.
Assuming your API request is valid, you would need to actually return something from the component itself and not just the array:
return datas.map((item) => {return <KurCard title={item.Isim} alis={item.BanknoteBuying} satis={item.BanknoteSelling}/>})

tfjs-node memory leak even after proper tensor disposal

I've struggling to find where a memory leak occurs in this file. This file is exported as an Event Listener. For context, I have 92 shards (meaning 92 of these listeners) running. I import the model from outside of this file so it's only loaded once per shard occurrence (stable 75 tensors in memory). However, after a few minutes, all the RAM on my computer is consumed (the function inside the file is called a dozen or so times per second). Have I overlooked any place which may cause this memory leak?
const use = require(`#tensorflow-models/universal-sentence-encoder`);
const tf = require(`#tensorflow/tfjs-node`);
const run = async (input, model) => {
const useObj = await use.load();
const encodings = [ await useObj.tokenizer.encode(input) ];
const indicesArr = encodings.map(function (arr, i) { return arr.map(function (d, index) { return [i, index]; }); });
var flattenedIndicesArr = [];
for (i = 0; i < indicesArr.length; i++) {
flattenedIndicesArr = flattenedIndicesArr.concat(indicesArr[i]);
}
const indices = tf.tensor2d(flattenedIndicesArr, [flattenedIndicesArr.length, 2], 'int32')
const value = tf.tensor1d(tf.util.flatten([ encodings ]), 'int32')
const prediction = await model.executeAsync({ Placeholder_1: indices, Placeholder: value });
const classes = [ 'Identity Attack', 'Insult', 'Obscene', 'Severe Toxicity', 'Sexual Explicit', 'Threat', 'Toxicity' ]
let finArr = [];
let finMsg = `Input: ${input}, `;
for (i = 0; i < prediction.length; i++) {
const sorted = tf.topk(prediction[i], 2);
const predictions = [ sorted.values.arraySync(), sorted.indices.arraySync() ];
const percentage = (predictions[0][0][0]*100).toFixed(2);
if (predictions[1][0][0] == 1) {
finArr.push(`${classes[i]} (${percentage}%)`);
}
tf.dispose([ sorted, predictions ]);
}
for (i = 0; i < finArr.length; i++) {
finMsg+=`${finArr[i]}, `;
}
tf.dispose([ prediction, indices, value, useObj ]);
console.log(finMsg);
console.log(tf.memory());
};
const main = async (message, client, Discord, model) => {
if (message.author.bot) return;
const input = message.content;
await run(input, model);
};
module.exports = {
event: 'messageCreate',
run: async (message, client, Discord, model) => {
await main(message, client, Discord, model);
},
};
to start with, you say this runs multiple times - so why are you loading model again and again? and disposing model is tricky, big chance that's part of your memory leak.
move const useObj = await use.load() outside of run loop and don't dispose it until you're done with all of the runs.

vue cli axios mixing array indexes when getting requests

const sentenc = this.colocation[0][i].examples;
sentenc.forEach((item,index) => {
var colAction = this.colocation[0][i].examples[index];
const strippedString = colAction.replace(/(<([^>]+)>)/gi, "");
this.examplesEN.push(strippedString)
axios.get('https://www.googleapis.com/language/translate/v2?key={apikey}='+strippedString+'&source=en&target=tr')
.then((response) =>{
const exTranslet = response.data.data.translations[0].translatedText;
this.examplesTR.push(exTranslet);
})
})
I am building a translator with using 2 different apis. While i pushing english colocations to array, cant pushing turkish colocations to another array to same index numbers. How can i fix it?
I don't know why but axios doing another loop selfly and mixing array indexes. For example;
for(i = 0; i<5; i++)
{
//your axios codes
{
//i = 0
//i = 3
//i = 2
//i = 4
//i = 1
}
//i = 0
//i = 1
//i = 2
//i = 3
//i = 4
}
You should push your all datas to array in axios. Like ;
const sentenc = this.colocation[0][i].examples;
sentenc.forEach((item,index) => {
var colAction = this.colocation[0][i].examples[index];
const strippedString = colAction.replace(/(<([^>]+)>)/gi, "");
axios.get('https://www.googleapis.com/language/translate/v2?key={apikey}='+strippedString+'&source=en&target=tr')
.then((response) =>{
const exTranslet = response.data.data.translations[0].translatedText;
this.examplesTR.push(exTranslet);
this.examplesEN.push(strippedString) //use this line in axios
})
})

$nextTick running before previous line finished

I have a vue function call which is triggered when selecting a radio button but it seems that my code inside my $nextTick is running before my previous line of code is finished. I don't want to use setTimout as I don't know how fast the user connection speed is.
findOrderer() {
axios.post('/MY/ENDPOINT')
.then((response) => {
this.orderers = response.data.accounts;
console.log('FIND_ORDER', this.orderers)
...OTHER_CODE
}
rbSelected(value) {
this.findOrderer();
this.newOrderList = [];
this.$nextTick(() => {
for (var i = 0, length = this.orderers.length; i < length; i++) {
console.log('FOR')
if (value.srcElement.value === this.orderers[i].accountType) {
console.log('IF')
this.newOrderList.push(this.orderers[i]);
}
}
this.$nextTick(() => {
this.orderers = [];
this.orderers = this.newOrderList;
console.log('orderers',this.orderers)
})
})
}
Looking at the console log the 'FINE_ORDERER' console.log is inside the 'findOrderer' function call so I would have expected this to be on top or am I miss using the $nextTick
That's expected, since findOrderer() contains asynchronous code. An easy way is to simply return the promise from the method, and then await it instead of waiting for next tick:
findOrderer() {
return axios.post('/MY/ENDPOINT')
.then((response) => {
this.orderers = response.data.accounts;
console.log('FIND_ORDER', this.orderers);
});
},
rbSelected: async function(value) {
// Wait for async operation to complete first!
await this.findOrderer();
this.newOrderList = [];
for (var i = 0, length = this.orderers.length; i < length; i++) {
console.log('FOR')
if (value.srcElement.value === this.orderers[i].accountType) {
console.log('IF')
this.newOrderList.push(this.orderers[i]);
}
}
this.orderers = [];
this.orderers = this.newOrderList;
console.log('orderers',this.orderers)
}

Debounce mobx-react and props

I'm trying to debounce the method call: "chart.calculateChartData(props.answers)".
I tried:
- autorun
- reaction
- use-debounce from a react lib.
- setTimeout within calculateChartData
Each solution led to an update cycle or didn't work because MobX is not immutable.
Has someone a hint?
function QuantificationChart(props: QuantificationChartProps) {
const {t} = useTranslation();
const rootStore = useRootStore();
const chart = rootStore.formulaStore.getChart<Chart>(Chart.chartName);
const data = chart.calculateChartData(props.answers);
calculateChartData = (questionData: { [id: string]: number; } = {}) => {
let chartData = [];
for (let i = 0; i < this.numberOfYears + 1; ++i) {
let customData = {...questionData, "year" : i};
let chartEntry = {
cost: this.rootStore.formulaStore.calculateFormula(this.cost.formula, customData),
earn: this.rootStore.formulaStore.calculateFormula(this.earn.formula, customData),
sum: 0
};
chartEntry.sum = (chartEntry.earn - chartEntry.cost) + (chartData[i - 1]?.sum || 0);
chartData.push(chartEntry);
}
return chartData;
};
Hint: It's my first project with MobX
Found a solution. Seems to work:
Based on: https://mobx-react.js.org/recipes-effects
const [data, setData] = React.useState(chart.calculateChartData(props.answers));
React.useEffect(
() =>
autorun(() => {
setData(chart.calculateChartData(props.answers));
}, {delay: 1000}),
[],
);