react native cant update state array in function - javascript

Im trying to push object into a state array in a function.But i cant, when i debug my array it is still empty..this.state = {
searchArray : [],}
here is my function
doSearch = (textinput) => {
let arrSearch = this.state.searchArray
//iterate model object
this.state.models[this.props.sexeModel].map(
(model) => {
let idmodel = model.id
//check if typed text is included in model name
if(model.nom.includes(textinput.SearchText)){
if(textinput.SearchText.length !== 0) {
//Checking if Search arr is empty
if(arrSearch.length === 0) {
let stateArray = this.state.searchArray
let joined = stateArray.concat(model)
this.setState({ searchArray: joined }) // CANT UPDATE HERE
} else {
arrSearch.map((modelSearch) => {
if(modelSearch.id == idmodel) {
console.log("Do not insert")
} else {
console.log("Insert")
let joined = arrSearch.concat(model)
this.setState({ arrSearch: joined })// CANTE UPDATE HERE
}
})
}
} else {
console.log("include but empty")
this.setState({searchArray:[]}) //CANT UPDATE HERE
}
} else {
console.log("not included")
this.setState({searchArray:[]}) // CANT UPDATE HERE
}
}
)
}
I can update a basic string or int/float state value in this function but not an array.Why ?
Any Ideas ?

Related

Check for duplicates in database before pushing item logic in JS

Can please someone let me know what's the issue with this code
I run get ref database and store results in obj, then if obj is empty we push new item. Otherwise I run a loop to see if item already exists.
The code not only doesn't follow any logic, but also push 3 items on third try, 4 on 4th and so on.
This is confusing, why it's not working, Checking for strings if equals I have implemented that not sure about the rest
saveIng = (item) => {
const reference = ref(
database,
"users/" + this.state.user + "/ingredients"
);
get(ref(database, "users/" + this.state.user + "/ingredients"))
.then((snapshot) => {
var obj = snapshot.val();
if (obj === null) {
push(reference, {
name: item,
});
} else {
for (let x in obj) {
var found = obj[x].name == item;
if (!found) {
continue;
} else {
push(reference, {
name: item,
});
}
}
}
})
.catch((error) => {
console.log(error);
});
};

Comparing data from JSON and input.value

I am working on small shopping cart project. I have products in JSON.file, also I have input for finding price of products.
I am using class method
question is: this are strings or numbers? -> (3) ['35', '35', '35']
searchItem(data) {
let that = this
searchBtn.addEventListener('click', function(e) {
const input = document.querySelector('.input').value
const findItem = data.filter(function(item) {
if(item.price === input) {
return item
}
}) // this return all data of product so I filtered only prices bellow
const getItem = findItem.map(item => {
return item.price
})
// this give: (3) ['35', '35', '35']
if(input === getItem) {
console.log('same')
} else {
console.log('try it again')
}
// this cond. show me : console.log('try it again')
// HOW TO GET: console.log('same')
e.preventDefault()
})
You can always run a typeof to find out what data types you dealing with
for example
console.log(typeof getItem[0])
also here :
if(input === getItem) {
console.log('same')
} else {
console.log('try it again')
}
you are checking the input variable against a whole array,you have to specify which item of the array to check against like :
if(input === getItem[0]) {
console.log('same')
} else {
console.log('try it again')
}
A quick and straight to your question without the code analysis, Any value gotten from your input is a string and not numbers.
Therefore, if the values of the price you are getting from data are integer, then you will have to consider parsing the values from the input by using the parseInt() method. Example;
const findItem = data.filter(function(item) {
if(item.price === parseInt(input)) {
return item
}
})
Another thing is that getItem is an array so, evaluating with a particular value from input is bound to fail. Therefore, use getItem[0] instead and two "==" instead of "===" just as suggested on the comment.
function searchItem(data) {
let that = this
searchBtn.addEventListener('click', function(e) {
const input = document.querySelector('.input').value
const findItem = data.filter(function(item) {
if(item.price == input) {
return item
}
}) // this return all data of product so I filtered only prices bellow
const getItem = findItem.map(item => {
return item.price
})
console.log(getItem);
// this give: (3) ['35', '35', '35']
if(input == getItem[0]) {
console.log('same')
} else {
console.log('try it again')
}
// this cond. show me : console.log('try it again')
// HOW TO GET: console.log('same')
e.preventDefault()
})
}

How to access a local variable's value in this situation?

I'm trying to read the number of times an event has been logged and increment/decrement a variable accordingly. Since I can't use this.setState inside the getPastEvent (because it generates an Unhandled Runtime Error which is TypeError: Cannot read property 'setState' of undefined), I'm opting for this method where I perform my counting on a local variable then save it to the state variable.
The issue here is when I use this.setState({totalBidders: biddersnumber}); at the end of the function, I receive the value zero where in my case it should be two! How can I get the value of the counter biddersnumber in this situation?
componentDidMount = async () => {
const accounts = await web3.eth.getAccounts();
const plasticBaleSC = plasticBaleContract(this.props.address);
var biddersnumber = 0;
var highestbid = 0;
plasticBaleSC.getPastEvents('allEvents', { fromBlock: 0, toBlock: 'latest' }, function (error, events) {
console.log(events);
events.forEach(myfunction);
function myfunction(item, index) {
if (item.event === 'bidderRegistered') {
console.log(item);
biddersnumber++;
//value is two here
console.log(biddersnumber);
} else if (item.event === 'bidPlaced') {
} else if (item.event === 'bidderRegistered') {
} else if (item.event === 'bidderExited') {
console.log(item);
biddersnumber--;
} else if (item.event === 'auctionStarted') {
}
}
});
//Value is zero here
this.setState({ totalBidders: biddersnumber });
}
Using comments on this question, I did the following updates to resolve the issue. Thank you Andrea!
componentDidMount = async () => {
const accounts = await web3.eth.getAccounts();
const plasticBaleSC = plasticBaleContract(this.props.address);
var biddersnumber = 0;
var highestbid =0;
plasticBaleSC.getPastEvents("allEvents",{fromBlock: 0, toBlock:'latest'},(error, events)=>{
console.log(events);
const myfunction = (item,index) => {
if(item.event==='bidderRegistered'){
console.log(item);
biddersnumber++;
console.log(biddersnumber);
}else if(item.event==='bidPlaced'){
}else if(item.event==='bidderRegistered'){
}else if (item.event==='bidderExited'){
console.log(item);
biddersnumber--;
}else if(item.event==='auctionStarted'){
//console.log(item);
//this.setState({highestBid: item.returnValues['startingAmount']});
}
};
events.forEach(myfunction);
this.setState({totalBidders: biddersnumber});
});
};
You need to put the call to setState inside your callback:
// ....
var highestbid =0;
const that = this
// ....
// Value is two here
that.setState({totalBidders: biddersnumber});
});
//Value is zero here
};
You'll need to deal with this, so assign it to that like it's 2010.

Why is javascript array object undefined after logging array contents to the console?

Trying to access and compare the value of an object's property inside my LobbyQueue class. I've successfully added data to the array from server.js, and logged it. but when I try to use a method from LobbyQueue class to access & compare an object's property value form the array, I get undefined for the array index.
I've tried looping through the array's contents from inside the Queue class. this is where I'm getting undefined's
LobbyQueue.js:
class LobbyQueue {
constructor() {
this.players = [];
}
enqueue(player) {
this.players.push(player);
}
dequeue() {
if (this.isEmpty()) {
return "Wait List is Empty";
}
return this.players.shift();
}
hasUser(username) {
if (this.players.length == 0) {
return false;
} else {
for (var i = 0; i < this.players.length; ++i) {
if (typeof this.players[i][username] === "undefined") {
console.log("this.players[" + i + "][username] is undefined...");
if (this.players[i][username] === username) {
console.log("username comparison entered...");
}
}
}
}
}
}
module.exports = LobbyQueue;
server.js:
const queue = new LobbyQueue();
var gameRooms = [];
io.on("connection", socket => {
console.log("a user connected..." + "\n");
socket.on("addPlayer", username => {
if (queue.hasUser(username)) {
console.log("user already in queue...");
} else {
console.log("New user joined: " + username);
queue.enqueue({
username: username,
id: socket.id
});
socket.join("lobby");
const players = queue.getAll();
console.log("Players in queue: " + "\n" + JSON.stringify(players));
io.sockets.in("lobby").emit("players", players);
}
});
...
I expect hasUser()to prevent a duplicate connection being created. but its not returning true when the username already exists in the queue. it's as if the user doesn't exist when it loops over the array. but since the queue was logged to the console and the username and connection id are there, Im not sure whats going on.
You need change condition to
typeof this.players[i]['username'] === "undefined"
Because you need access property name 'username'
for (var i = 0; i < this.players.length; ++i) {
if (typeof this.players[i]['username'] === "undefined") {
console.log("this.players[" + i + "][username] is undefined...");
if (this.players[i]['username'] === username) {
console.log("username comparison entered...");
}
}
}
hasPlayer(username) {
return this.players.find(player => player['username'] == username) != null;
}

How to add value to array after checking another array

I have two arrays as such :
UserGroupUser[{Id:"1",UserId:"2",UserGroupId"1"},
{Id:"2",UserId:"3",UserGroupId"1"},
{Id:"3",UserId:"4",UserGroupId"2"}]
UserGroupId will have values such as 1, 2, 3 etc.
Employee[{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
I will store a number in a variable GroupId such as GroupId=1
and what i want to do is check the UserGroupUser table if GroupId 1 matches any rows for key UserGroupId and if there is a match for every UserId the corresponding EmployeeId in Employee table that matches would mean i add a new element called enrolled=true. else if there is not match add a element to Employee enrolled=false.
for eg:
If GroupId is =1 then i want to get the userId of those with the UserGroupId as 1 in the UserGroupUser array and add enrolled:true into the Employee array EmployeeId to those corresponding to the UserId .
This is how i tried to do it..
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
result = Employee.map(function (a, index, array) {
while (arrayItem.UserId === a.EmployeeNo) {
a.enrolled = true;
}
return a;
}
);
}
else {
result = Employee.map(function (a, index, array) {
a.enrolled = false;
return a;
}
);
}
});
what am i doing wrong? how should i do this?
Try this
var userGroup = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}]
var employees = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
employees.forEach(function(item){
var found = userGroup.filter(i=>i.UserId==item.Id);
if(found.length>0)
item.enrolled = true
else
item.enrolled = false
})
console.log(employees);
the employees then will contained the enrolled or not try this in your console too
The problem with your code is that when if (arrayItem.UserGroupId === GroupId) { is executed, it changes enrolled to true for the concerned employees but when the else part of this check is executed, it overrides the changes made by the if condition part.
Try this.
UserGroupUser = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}];
Employee = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"}];
GroupId = "1";
Employee.map(function (emp) {
emp.enrolled = false;
});
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
Employee.map(function (emp) {
if (arrayItem.UserId === emp.EmployeeId) {
emp.enrolled = true;
}
});
}
});
console.log(Employee);

Categories

Resources