Cannot set setstate in reactJS - reactjs

Can anybody explain what im doing wrong here, my setState console is returning undefined where the first console is returning right values
return firebase.database().ref('Users/Trainers/').on('value', (snapshot) => {
snapshot.forEach(function(childSnapshot){
// var childKey= childSnapshot.key;
var childData= childSnapshot.val();
var childEmail = childData.email;
var childfirstName = childData.firstName;
var childlastName = childData.lastName;
var childTrainers = childfirstName + ' ' + childlastName + ' ' + childEmail;
console.log(childTrainers);
})
this.setState({
Trainers: snapshot.val().childTrainers
})
console.log(this.state.Trainers)
})

Okay ive done, and the correct answer is
return firebase.database().ref('Users/Trainers/').on('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
// this.setState({
// childEmail = childSnapshot.val().email
// })
// var childKey= childSnapshot.key;
var childData= childSnapshot.val();
var childEmail = childData.email;
var childfirstName = childData.firstName;
var childlastName = childData.lastName;
var childTrainers = childfirstName + ' ' + childlastName + ' ' + childEmail;
//console.log(childTrainers);
this.setState({
Trainers: [childTrainers]
}, console.log(this.state.Trainers))
})
})
All values are retrieving

Related

Repetitive data when loading a select

I'm calling EventListener so that when something is typed into the username field, it will list that user's companies for me.
var ent = document.getElementById("username");
//var str = "";
ent.addEventListener('change', async () => {
localStorage.clear();
self.empUsuario = new Array();
self.rucEmp = new Array();
var newUser = document.getElementById("username");
$('#empresa').empty();
await fetch(environment.apiPoint + '/empresas?usuario=' + newUser.value, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(datos => {
datos.forEach(e => {
self.todasEmpresasUsuario.push({
ruc: e.ruc,
nombEmp: e.nombreCorto
});
});
})
await self.todasEmpresasUsuario().forEach(
function (element) {
self.empUsuario.push(element.nombEmp);
self.rucEmp.push(element.ruc);
}
);
Then I give it a conditional if the user is different from null, that it shows me with the rucEmp, and if not an empty space.
var str = "";
var item = "";
if (newUser.value != '') {
self.cont = 0;
let vacio = '';
for (item of self.empUsuario) {
vacio = "<option value=''>" + ' ' + "</option>"
str += "<option value='" + self.rucEmp[self.cont] + "'>" + item + "</option>"
self.cont++;
}
if (newUser.value == '') {
//str += "";
str += "<option value='" + self.rucEmp[self.cont] + "'>" + item + "</option>"
$('#empresa').empty().append(str);
}
$('#empresa').empty().append(vacio + str);
}
I expected the company lists to appear for each user and not accumulate, but the lists accumulate in the select.
enter image description here

DiscordJS role set returns API Error: Missing Permissions

I try to set the member roles, but it doesn't set the permissions.
My index.js file:
var u, s, m;
await bot.users.fetch(message.author.id)
.then(user => { u = user; });
await bot.guilds.fetch('419248578121433100')
.then(guild => { s = guild; });
await s.members.fetch(u)
.then(member => { m = member; });
axios.get('/process')
.then(function (response)
{
var dptos = response.data.dptos;
var attrs = response.data.userAttrs;
var roles = response.data.roles;
if(dptos.length > 0) m.setNickname(dptos[0].position + ' | ' + attrs.name + ' ' + attrs.surname);
else m.setNickname(attrs.name + ' ' + attrs.surname + ' | ' + '123456');
m.roles.set(roles)
.then(function(member)
{
let fd = fs.openSync('log.txt', 'w');
fs.writeSync(fd, JSON.stringify(member.roles.cache));
fs.closeSync(fd);
})
.catch(function(error)
{
let fd = fs.openSync('error.txt', 'w');
fs.writeSync(fd, error);
fs.closeSync(fd);
});
return message.reply('Congrats!');
})
.catch(function (error)
{
return message.reply('error!');
});
}
The axios request works as expected and the data is obtained correctly.
Screenshots:
Bot position
Bot general permissions
UPDATE 1: Nickname permissions
What could be the issue?

How to insert the q_auto in cloudinary url from variable in reactjs

I'm having trouble in inserting the "q_auto" in cloudinary variable. I will give some code.
let photoUrl = {
url = https://res.cloudinary.com/demo/image/upload/w_600/beach_huts.jpg
}
let finalUrl = ..... some code;
I want that in variable finalUrl is like has "q_auto", of course that's only example but lets just say that I don't know the url given my server.How can I do it ?
I think this is what you are looking for.
let photoUrl = {
url: 'https://res.cloudinary.com/demo/image/upload/w_600/beach_huts.jpg'
};
let insertText = 'q_auto/';
let searchText = "res.cloudinary.com/demo/image/upload/";
let position = photoUrl.url.indexOf(searchText);
let insertPosition = position + searchText.length;
var output = [photoUrl.url.slice(0, insertPosition), insertText, photoUrl.url.slice(insertPosition)].join('');
console.log(output); // https://res.cloudinary.com/demo/image/upload/q_auto/w_600/beach_huts.jpg
Not sure if you are looking for this answer.
let photoUrl = {
url: 'https://res.cloudinary.com/demo/image/upload/w_600/beach_huts.jpg'
}
var params = {
param1: 'value1',
param2: 'value2'
}
let appendedUrl = '';
for(let key in params) {
if(appendedUrl) {
appendedUrl = appendedUrl + '&';
} else {
appendedUrl = appendedUrl + '?';
}
appendedUrl = appendedUrl + key + '=' + params[key]
}
let finalUrl = photoUrl.url + appendedUrl;

code in promise .then firing way before promise finishes

I have this code...sorry for the messiness I've been at this a while:
loadAvailabilities() {
let promises = [];
let promises2 = [];
let indexi = 0;
//return new Promise((resolve, reject) => {
this.appointments = this.af.list('/appointments', { query: {
orderByChild: 'selected',
limitToFirst: 10
}});
let mapped;
this.subscription2 = this.appointments.subscribe(items => items.forEach(item => {
//promises.push(new Promise((resolve, reject) => {
console.log(item);
let userName = item.$key;
//this.availabilities = [];
for(let x in item) {
let month = x;
console.log(x + " month");
this.appointmentsMonth = this.af.list('/appointments/' + userName + '/' + month);
this.subscription3 = this.appointmentsMonth.subscribe(items => items.forEach(item => {
this.startAtKeyAvail = item.$key;
//console.log(JSON.stringify(item) + " item");
let date = new Date(item.date.day * 1000);
let today = new Date();
console.log(date.getMonth() + "==" + today.getMonth() + "&&" + date.getDate() + "==" + today.getDate());
console.log("IN LOAD AVAILABILITIES *(*((**(*(*(*(*(*(*&^^^^%^%556565656565");
if(date.getMonth() == today.getMonth() && date.getDate() == today.getDate()) {
console.log(" inside the if that checks if its today");
console.log(item.reserved.appointment + " *************appointment");
//let counter = 0;
//mapped = item.reserved.appointment.map((r) => {
//item.reserved.appointment.forEach((r, index) => {
for(let r of item.reserved.appointment) {
promises.push(new Promise((resolve, reject) => {
if(r.selected == true) {
//this.renderer.setElementStyle(this.noavail.nativeElement, 'display', 'none');
let storageRef = firebase.storage().ref().child('/settings/' + userName + '/profilepicture.png');
let obj = {'pic':"", 'salon': userName, 'time': r.time};
storageRef.getDownloadURL().then(url => {
console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
obj.pic = url;
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
}).catch((e) => {
console.log("in caught url !!!!!!!$$$$$$$!!");
obj.pic = 'assets/blankprof.png';
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
});
}
}))
}
}
}))
}
}))
//}));
Promise.all(promises).then(() => {
console.log("in load availabilities ......... ")
console.log(JSON.stringify(this.availabilities));
this.availabilities.sort(function(a,b) {
return Date.parse('01/01/2013 '+a.time) - Date.parse('01/01/2013 '+b.time);
});
console.log('*****previous******');
console.log(JSON.stringify(this.availabilities));
console.log('*****sorted********');
for(let i of this.availabilities) {
console.log(i.time + " this is itime");
let date = new Date('01/01/2013 ' + i.time);
console.log(date + " this is date in idate");
let str = date.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
console.log(str);
i.time = str;
}
});
//}))
//})
}
I can tell from the log messages that the storageRef.getDownloadURL() function happens close to the end of when my page loads...this is where the objects actually get pushed to this.availabilities (eventually used to populate a list). The code in the Promise.all .then() actually fires before anything gets pushed to this.availabilities so when the sorting happens it is an empty array and nothing gets sorted.
I used a promise inside each forEach loop. I pushed all the promises to the same array and used Promise.all(array).then(...) how it is being used above - and the promises did their job - the array is sorted because everything is happening asynchronously.

code passes through $scope.options first instead of $http.get

i have an ion-slide component with 3 slides. when running the app the first time, all three slides load. however, going to another controller and coming back to the controller where the ion-slide is (using $state.go), only displays one slide and has the following error:
TypeError: Cannot read property '0' of undefined
seeing this error, i traced it passes through this line first:
sharedProperties.setProperty($scope.cardNumbers[$scope.currentIdx]
.CardNumber);
instead of this code fetching the card number:
var url = 'http://10.10.9.169/UserService3/WebService1.asmx';
$http.get(url + '/getCardsbyUsername' + '?unameID=' + currentID ).success(function(response) {
// stuff
console.log('response is jsonobj = ' + response);
var strObj = JSON.stringify(response).replace(/"(\w+)"\s*:/g, '$1:');
var myObject = eval('(' + strObj + ')');
$scope.cardNumbers = myObject;
console.log('response is jsonarr = ' + $scope.cardNumbers);
})
.error(function(response) {
// error stuff
console.log('response error is = ' + response);
});
here's the full code:
$scope.currentIdx = 0;
var currentID = sharedProperties3.getUserID();
console.log('current ID = ' + currentID);
var url = 'http://10.10.9.169/UserService3/WebService1.asmx';
$http.get(url + '/getCardsbyUsername' + '?unameID=' + currentID ).success(function(response) {
// stuff
console.log('response is jsonobj = ' + response);
var strObj = JSON.stringify(response).replace(/"(\w+)"\s*:/g, '$1:');
var myObject = eval('(' + strObj + ')');
$scope.cardNumbers = myObject;
console.log('response is jsonarr = ' + $scope.cardNumbers);
})
.error(function(response) {
// error stuff
console.log('response error is = ' + response);
});
$scope.options1 = {
initialSlide: 0,
onInit: function(slider1)
{
$scope.slider1 = slider1;
sharedProperties.setProperty($scope.cardNumbers[$scope.currentIdx].CardNumber);
},
onSlideChangeEnd: function(slider1)
{
console.log('The active index is ' + slider1.activeIndex);
$scope.currentIdx = slider1.activeIndex;
console.log('The active card is ' + $scope.cardNumbers[$scope.currentIdx].CardNumber);
sharedProperties.setProperty($scope.cardNumbers[$scope.currentIdx].CardNumber);
}
};
$scope.options2 = {
direction: 'vertical',
slidesPerView: '1',
pagination: false,
initialSlide: 1,
showNavButtons: false
};
how can i make it pass through the $http.get code block first?
i noticed i was loading angularjs more than once, so i got rid of the extra code calling angularjs in my index.html and it worked.

Resources