Use passed parameters in for loop - React Native - loops

I have two classes. In the first one I am fetching from an API. Then I am passing the data to the other class using props.navigation. I can display the data but I want to use those data in a For loop as in this code:
renderText = () => {
const obje = this.props.navigation.state.params.item;
Console.log(obje) //this prints correctly
for (let i = 0; i < obje.length; i++) {
console.log(obje) //this doesnt print anything
if (obje[i].name != null) {
console.log(obje}
}
}
EDIT:
When I try to print const obje, it prints. But when I try to print obje inside the for loop it doesnt, so I guess its not even going through the for loop at all.

Try this way:
renderText = () => {
const obje = this.props.navigation.state.params.item;
console.log(obje) //this prints correctly
Object.keys(obje).map((item) => {
if(item == 'name'){
console.log(obje[item])//YOU CAN PRINT NAME'S VALUE LIKE THIS
}
})
}

Related

Adding another check property to select default rows on antd table

Currently i have this code on my api call to add a check property (list) (based on api called data "resRole" and "res") which can be used inside of rowSelection to select all the default checked row.
However, now i have another table which I need to do the same thing. Just that instead of using resRole, now I will use resProject. Which i need to first add a key to, before i add a checkProject in "res".
As such, i updated the check to checkRole and intend to put in an additional checkDept (list) in the getAllUserRole's res.data.
Looking at my code, I do not know where I can implement it. It seems like I have to create it inside of the getDataUserRole() function but that seems too messy. And might cause some async issues.
Below is the code:
async function getDataProject() {
let resProject = await getAllProject();
if (resProject) {
setDataSourceProject(resProject.data);
}
}
async function getDataUserRole() {
let resRole = await getAllRoles();
if (resRole) {
//Add a key to every Role
for (var i = 0; i < resRole.data.length; i++) {
resRole.data[i]["key"] = i;
}
setDataSourceRole(resRole.data);
let res = await getAllUserRole();
if (res) {
console.log("getAllUserRole =", res);
for (var i = 0; i < res.data.length; i++) {
//add "check" to every email in the array
res.data[i]["checkRole"] = [];
//loop through all the roleIds array in each email
for (var j = 0; j < res.data[i].roleIds.length; j++) {
//if roleIds is not empty
if (res.data[i].roleIds.length != 0) {
//loop through all Role from getAllRoles and check if any roleIds match the Role. If match push the key of the Role into check
for (var k = 0; k < resRole.data.length; k++) {
if (res.data[i].roleIds[j] == resRole.data[k].id) {
res.data[i]["checkRole"].push(resRole.data[k].key);
}
}
}
}
}
//If groupChange (groupChange is state for storing value of radio button) is null, return untransformed data
if (!(groupChange)) {
setDataSourceUserRole(res.data);
}
//If groupChange has value, call the function with the state value as a parameter
else {
var treeData = groupData(res.data, groupChange)
setDataSourceUserRole(treeData);
}
}
}
}
Instead of Using it inside getDataUserRole(). Use it inside getAllUserRole(). and once you get your result just add additional data with the role and send it back to one function.
If you want to call it separately so then you to depend it one function on another because due to async it will not work properly

How is useState() updating my data here? STRANGE

I have data from an movie-api I want to sort based on a select menu, either by year in descending order or title in alphabetical order.
Although Im only updating state in the sort function, not using the variable any where, the data thats already mapped out, and in a different array, updates accordingly. I guess its somehow related to the first change in state for each of the two differen variables?
Any idea how I should solve this correctly and why this is happening?
const sortData = (e) => {
if (e === "year"){
const yearData = data.sort(function(a, b) {
const yearA = a.Year;
const yearB = b.Year;
if (yearA < yearB) {
return -1;
}
if (yearA > yearB) {
return 1;
}
return 0;
});
setYearData(yearData);
}
if (e === "title") {
const titleData = data.sort(function(a, b) {
const titleA = a.Title.toUpperCase();
const titleB = b.Title.toUpperCase();
if (titleA < titleB) {
return -1;
}
if (titleA > titleB) {
return 1;
}
return 0;
});
setTitleData(titleData);
}
}
The sort() method sorts the elements of an array in place, so the data(state) changed without using setState (It may cause some unpredictability happened in the execution)
You can use the sort() method on a copy of the array, so it doesn't affect your state array, I guess this change may work:
use [...data].sort(...) instead of data.sort(...)
Array.sort(), in your case data.sort() updates the original array in addition to returning it. Seems like your data variable is some sort of global that gets changed during sort().

Not able to state with react typed.js callbacks

I'm trying to update a counter located in the state every time the type string changes with this node module. When I'm attaching the preStringTyped function to the component, the function (the alert located in the preStringTyped) triggers only once.
Here's the module: https://github.com/ssbeefeater/react-typed
Here's my code - you can ignore the randomlySelectElements and the displayTweets function, what matters here is the preStringTyped and what is inside the return().
preStringTyped = () => {
alert("typed")
}
randomlySelectElements = (number, array) => {
let shuffedArray = _.shuffle(array);
let selectedEle = shuffedArray.slice(0, number);
return selectedEle;
}
displayTweets = () => {
if(!this.state.rawData){
return null
}else{
let getRandomTweetsStrings = () => {
return this.randomlySelectElements(10, this.state.rawData)
.map((ele, index) => {
return ele.masterData.randomString
})
}
return (
<ReactTyped
loop
typeSpeed={50}
backSpeed={20}
strings={
getRandomTweetsStrings()
}
smartBackspace
backDelay={1}
fadeOutDelay={100}
loopCount={0}
showCursor
cursorChar="|"
onBegin={this.preStringTyped()}
/>
)
}
}
First you need to use preStringTyped callback (not onBegin) that will be triggered before each string is typed. Also in your code you emidiatly execute the function this.preStringTyped() but you should pass it as a reference to the callback property (preStringTyped={this.preStringTyped}). Your code should be like this
<ReactTyped
loop
typeSpeed={50}
backSpeed={20}
strings={
getRandomTweetsStrings()
}
smartBackspace
backDelay={1}
fadeOutDelay={100}
loopCount={0}
showCursor
cursorChar="|"
preStringTyped={this.preStringTyped} // <- not onBegin={this.preStringTyped()}
/>

cannot parseInt in React project keep getting NaN

Ok, so I am currently trying to add items from an object together prices to be exact. When I try to actually parse the items with parseInt,I keep getting NaN.
I have tried to replicate it on repl.it and it works fine, also I have tried to use Number instead of parseInt and same results.
class Cart extends Component {
constructor(props) {
super(props);
this.add = this.add.bind(this);
}
componentDidMount() {
this.props.getCart();
}
add(array) {
let num = [];
let parse = [];
console.log(array);
for (let i = 0; i < array.length; i++) {
parse.push(array[i].price);
}
console.log(parse);
for (let i = 0; i < parse.length; i++) {
num.push(parseInt(parse[i]));
}
console.log(num);
let sum = num.reduce((acc, val) => {
return acc + val;
}, 0);
console.log(sum);
}
render() {
const { cart } = this.props.itemReducer;
this.add(cart);
I do have a few console.log's
first one does show my obj's
the second show's that I pulled my numbers in the variable["$379.99", "$1,499.99"]
the third one where I actually do the parseInt function is when i get [NaN, NaN]`
There is a $ sign in your string. Remove the sign and try
let nanNum = parseInt("$1477")
console.log(nanNum) //This will print NaN
let parsedNum = parseInt("$147,7.05".replace(/[^0-9\.]+/g,""))
console.log(parsedNum)
This is because of ["$379.99", "$1,499.99"], here items in array contains $ which is not a number (NaN) causing the error.
Instead of this,
num.push(parseInt(parse[i]));
You can do this,
num.push(Number(parse[i].replace(/[^0-9.]/g, "")));
Demo

AngularJS .destroy() shows console error, but works?

I use destroy() function something like this:
$scope.Cities[i].destroy();
Then when I use it my app works fine, but the console says:
$scope.Cities[i] is undefined
However without it, it doesn't work. Should I ignore the error?
MORE CODE
$scope.Somefunction= function (id) {
for (var i = 0; i < $scope.Cities.length; i++) {
if ($scope.Cities[i] == id) {
$scope.SpliceCities(i);
$scope.Cities[i].destroy();
}
}
$scope.SpliceCities = function(i) {
$scope.Cities.splice(i, 1);
};
}
Function is called on ng-click on country.
splice mutates the array, so the i index points to another element when calling destroy(). If i pointed to the last element before the splice, you get this error. Fortunately splice also returns the elements that were spliced out as an array, so try this:
$scope.Somefunction = function (id) {
for (var i = 0; i < $scope.Cities.length; i++) {
if ($scope.Cities[i].id == id) {
var spliced = $scope.Cities.splice(i, 1);
spliced[0].destroy();
break;
}
}
}

Resources