Asynchronous Function In NextAuth Completing Before Value Returned - reactjs

On signin, I'm attempting to query FirestoreDB and then return the user data or null.
I'm trying to do this with async await, but the dependent code runs before the db query has been completed. This can be seen when "CORRECT," (right credentials) is console logged after the empty user details (not complete).
Thanks,
This is my code:
let data = await db.collection('users').where("email", "==", email).get().then(querySnapshot => {
console.log("SOMETHING")
let arr = []
querySnapshot.docs.map(doc => arr.push(doc.data()))
console.log(arr)
// console.log(sc.decrypt(arr[0].password))
if (arr[0].email == email) {
bcrypt.compare(password, arr[0].password, (err, match) => {
if (match) {
console.log("CORRECT")
return arr[0]
} else {
if (err) {
console.log(err)
}
console.log("INCORRECT")
return null
}
})
}
})
console.log("DATA " + data)
return data ? data : null

An hour of searching, but 2 minutes after I post I figure it out.
Here is the working code for anyone in the same boat:
let data = new Promise((resolve, reject) => {
db.collection('users').where("email", "==", email).get().then(querySnapshot => {
console.log("SOMETHING")
let arr = []
querySnapshot.docs.map(doc => arr.push(doc.data()))
console.log(arr)
// console.log(sc.decrypt(arr[0].password))
if (arr[0].email == email) {
bcrypt.compare(password, arr[0].password, (err, match) => {
if (match) {
console.log("CORRECT")
resolve(arr[0])
} else {
if (err) {
console.log(err)
}
console.log("INCORRECT")
resolve(null)
}
})
}
})
})
Promise.all([data]).then(async () => {
console.log(await data)
})
return data ? data : null

Related

How to compare member id and bots id on the server

I get the ids of all bots on the server but I can't compare them with the user id
How do I do this?
-- Comment --
I know that I can't compare the user id with the id of all bots just by writing this, but I don't know how to compare the user id with each id in the list
-- Part of the code --
module.exports = {
data: new SlashCommandBuilder()
.setName("pay")
.setDescription("🥁│Дать деньги другому пользователю")
.addNumberOption((option) => option.setName("amount").setDescription("🧩│Кол-во денег которое хочешь перевести").setRequired(true))
.addUserOption((option) => option.setName("target").setDescription("🎯│Выбрать кому перевести деньги").setRequired(true))
.setDefaultMemberPermissions(PermissionFlagsBits.SendMessages),
async execute(interaction) {
const target = interaction.options.getUser("target")
const member = await interaction.guild.members.cache.get(target.id)
const bots = await interaction.guild.members.cache.filter(m => m.user.bot).map(i => i.user.id)
if (!member) {
await interaction.reply({ content: "**🧩│The user is not identified or he has left the server**" }).then(() => {
setTimeout(async () => {
await interaction.deleteReply().catch((error) => {
if (error.code !== RESTJSONErrorCodes.UnknownMessage) {
return
} else {
return
}
})
}, ms("3s"))
})
} else if (member.user.id == interaction.user.id) {
await interaction.reply({ content: "**🧩│You can't transfer money to yourself**" }).then(() => {
setTimeout(async () => {
await interaction.deleteReply().catch((error) => {
if (error.code !== RESTJSONErrorCodes.UnknownMessage) {
return
} else {
return
}
})
}, ms("3s"))
})
} else if (member.user.id == bots || member.user.id == interaction.guild.members.me.id) {
await interaction.reply({ content: "**🧩│You can't transfer money to a bot**" }).then(() => {
setTimeout(async () => {
await interaction.deleteReply().catch((error) => {
if (error.code !== RESTJSONErrorCodes.UnknownMessage) {
return;
} else {
return;
}
})
}, ms("3s"))
})
}
}
}
There is a .bot property on the User Class which you can use like this:
if(member.user.bot) {
// Do something if bot
}
Using this, will be easier to check whether the user is a bot or not.

How to make a PATCH request in ReactJS ? (with Nestjs)

nestjs controller.ts
#Patch(':id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
#Body('shippingAddr') addrShipping: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling, addrShipping);
return null;
}
nestjs service.ts
async updateProduct(
addressId: string,
addrBilling: boolean,
addrShipping: boolean,
) {
const updatedProduct = await this.findAddress(addressId);
if (addrBilling) {
updatedProduct.billingAddr = addrBilling;
}
if (addrShipping) {
updatedProduct.shippingAddr = addrShipping;
}
updatedProduct.save();
}
there is no problem here. I can patch in localhost:8000/address/addressid in postman and change billingAddr to true or false.the backend is working properly.
how can i call react with axios?
page.js
const ChangeBillingAddress = async (param,param2) => {
try {
await authService.setBilling(param,param2).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
return....
<Button size='sm' variant={data.billingAddr === true ? ("outline-secondary") : ("info")} onClick={() => ChangeBillingAddress (data._id,data.billingAddr)}>
auth.service.js
const setBilling = async (param,param2) => {
let adressid = `${param}`;
const url = `http://localhost:8001/address/`+ adressid ;
return axios.patch(url,param, param2).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}
I have to make sure the parameters are the billlingddress field and change it to true.
I can't make any changes when react button click
Since patch method is working fine in postman, and server is also working fine, here's a tip for frontend debugging
Hard code url id and replace param with hard coded values too:
const setBilling = async (param,param2) => {
// let adressid = `${param}`;
const url = `http://localhost:8001/address/123`; // hard code a addressid
return axios.patch(url,param, param2).then((response) => { // hard code params too
console.log(response); // see console result
if (response.data.token) {
// localStorage.setItem("user", JSON.stringify(response.data));
}
// return response.data;
})
}
now it worked correctly
#Patch('/:id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling);
return null;
}
const ChangeBillingAddress = async (param) => {
try {
await authService.setBilling(param,true).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
const setBilling= async (param,param2) => {
let id = `${param}`;
const url = `http://localhost:8001/address/`+ id;
return axios.patch(url,{billingAddr: param2}).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}

How to get a single document from firestore?

According to the documentation from firebase you can get a document very simply by using get()
But for some reason in my code it always displays that there's no such document, even though it does exist, this is what I'm doing:
useEffect(() => {
console.log(user, "This is the user UID:"+user.uid)
const userDoc = db.collection('usuarios').doc(user.uid);
const doc = userDoc.get();
if (!doc.exists) {
console.log('No such document!');
}
else {
userDoc
.onSnapshot(snapshot => {
const tempData = [];
snapshot.forEach((doc) => {
const data = doc.data();
tempData.push(data);
});
setUserData(tempData);
})
}
}, [user]);
This is what the console.log() shows:
This is how it looks in firebase:
const doc = userDoc.get();
if (!doc.exists) {
.get returns a promise, so you're checking the .exists property on a promise, which is undefined. You will need to wait for that promise to resolve, either with .then:
userDoc.get().then(doc => {
if (!doc.exists) {
// etc
}
});
Or by putting your code in an async function and awaiting the promise:
const doc = await userDoc.get();
if (!doc.exists) {
// etc
}
If you're using the firebase 8 web version, the userDoc.get() returns a promise, not the document:
userDoc.get().then((doc) => {
if (!doc.exists) {
console.log('No such document!');
} else {
const tempData = [];
const data = doc.data();
tempData.push(data);
setUserData(tempData)
console.log('it worked')
}
}).catch((error) => {
console.log("Error getting document:", error);
});
You can get more info about promises in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises.
In your code you are using the get method to fetch user data and get doesn't provide a snapshot. also, you missed that get() will return a promise so you have to handle using async-await or .then etc.
useEffect(() => {
console.log(user, "This is the user UID:"+user.uid);
getUser(user.uid).then(userData => {
setUserData(userData);
});
}, [user]);
const getUser = async (id) => {
try {
const user = await db.collection('usuarios').doc(id).get();
const userData = user.data();
return userData;
} catch (err){
console.log('Error during get user, No such document!');
return false;
}

How can i get the result of a function in React Native

Im not getting the result of a database query, instead im getting 'undefined'
Can someone pls tell me what im missing here?
DbManager.js
getCameras() {
db.transaction(tx => {
tx.executeSql('select * from cameras;', [],
(_, result) => { return result.rows._array });
});
}
App.Js
async componentDidMount() {
dbManager.createDatabase();
//dbManager.insertCamera('Canon Canonet QL 17');
let data = await dbManager.getCameras();
console.log(data);
}
You need to return a Promise and resolve with the result.
getCameras() {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql('select * from cameras;', [], (_, result) => {
resolve(result.rows._array)
});
});
})
}
async componentDidMount() {
dbManager.createDatabase();
//dbManager.insertCamera('Canon Canonet QL 17');
let data = await dbManager.getCameras();
console.log(data);
}

action is triggering a series of remote methods and returning rejected

I have an action that is getting dispatched that is triggering multiple remote methods and returning'TALK_SUBMIT_REJECTED' The strange thing however, is that all of the data that I am getting is still returned and updating the store as expected.
I am however getting these two errors in the process:
xhr.js:178 POST http://localhost:3000/api/talks/talkSubmit 500
(Internal Server Error)
createError.js:16 Uncaught (in promise) Error: Request failed with
status code 500
at e.exports (createError.js:16)
at e.exports (settle.js:18)
at XMLHttpRequest.m.(:3000/anonymous function)
(http://localhost:3000/bundle.js:6:2169)
I have thrown in two dozen console.logs recording all of the data I am sending and receiving and everything returning as expected.
I apologize in advance for the long post but I have been struggling with this bug for a while.
to give a brief summery of what my code is doing:
I have a form that upon submission, triggers an action that starts a chain of remote methods.
This is the first method:
function talkSubmit(speakerInfo, talkInfo, date) {
return new Promise((resolve, reject) => {
const { Talk, Speaker, Event } = app.models;
return Speaker.create(speakerInfo)
.then(response => {
let speakerId = response.id
return getMeetups()
.then(meetups => {
const index = meetups.findIndex((item) =>
item.date == date);
let name = meetups[index].name;
let details = meetups[index].description;
let meetupId = meetups[index].meetupId;
if (index === -1)
return reject(new Error('NO meetup with that
date found!'));
return Event.findOrCreate({ date, name, details,
meetupId })
.then(event => {
let eventId = event[0].id
return Talk.create({ ...talkInfo,
speakerId, eventId })
.then(talk => resolve(talk))
.catch(err => console.log(err))
})
.catch(err => reject(err))
})
.catch(err => reject(err))
})
.catch(err => reject(err))
})
}
module.exports = { talkSubmit };
//this is the get meetups function that is called by talkSubmit
function getMeetups() {
return new Promise((resolve, reject) => {
let currentDate = new Date();
currentDate.setMonth(currentDate.getMonth() + 3);
const date ='${ currentDate.getFullYear() } -${
currentDate.getMonth() } -${
currentDate.
getDay()
} ';
axios.get(`https://api.meetup.com/sandiegojs/events?
no_later_than = ${ date } `)
return resolve(response.data.map(event => ({
meetupId: event.id,
name: event.name,
date: event.local_date,
time: event.local_time,
link: event.link,
description: event.description,
})))
.catch(err => reject(new Error('getMeetups failed to get SDJS
meetups')))
})
}
module.exports = { getMeetups };
//This is the after remote method that is triggered when talkSubmit is
//completed.
Talk.afterRemote('talkSubmit', function (ctx, modelInstance, next) {
const speakerId = ctx.result.speakerId;
const eventId = ctx.result.eventId;
const approved = false;
const pending = true;
formatTalkForEmail(speakerId, eventId)
.then((response) => {
const speakerName = response.speakerName;
const speakerEmail = response.speakerEmail;
const meetupTitle = response.meetupTitle;
const meetupDate = response.meetupDate;
sendEmailToSpeaker(process.env.ADMIN_EMAIL, approved,
pending, speakerEmail, speakerName, meetupTitle, meetupDate)
.then(() => next())
.catch(err => next(err));
})
.catch(err => next(err));
});
//this is the formatTalkForEmail method called in the remote method
function formatTalkForEmail(speakerId, eventId) {
return new Promise((resolve, reject) => {
if (speakerId == undefined) {
return reject(new Error('speakerId is undefined'));
}
if (eventId == undefined) {
return reject(new Error('eventId is undefined'));
}
const { Speaker, Event } = app.models;
Speaker.findById(speakerId)
.then(speaker => {
const speakerName = speaker.speakerName;
const speakerEmail = speaker.speakerEmail
return Event.findById(eventId)
.then(selectedEvent => {
const meetupTitle = selectedEvent.name;
const meetupDate = selectedEvent.date;
resolve({
speakerName,
speakerEmail,
meetupTitle,
meetupDate
})
})
.catch(err => reject( err ))
})
.catch(err => reject(err))
})
}
module.exports = { formatTalkForEmail };
//and finally this is the sendEmailToSpeaker method:
function sendEmailToSpeaker(adminEmail, approved, pending,
speakerEmail, speakerName, meetupTitle, meetupDate) {
return new Promise((resolve, reject) => {
let emailContent;
if (approved && !pending) {
emailContent = `Congratulations! Your request to speak at
${ meetupTitle } on ${ meetupDate } has been approved.`
}
if (!approved && !pending) {
emailContent = `We're sorry your request to speak at
${ meetupTitle } on ${ meetupDate } has been denied.`
}
if (pending) {
emailContent = `Thank you for signing up to speak
${ meetupTitle } on ${ meetupDate }.You will be notified as soon as
a
SDJS admin reviews your request.`
sendEmailToAdmin(adminEmail, meetupDate, meetupTitle,
speakerEmail, speakerName)
.catch(err => console.log(err));
}
const email = {
to: speakerEmail,
from: adminEmail,
subject: 'SDJS Meetup Speaker Request',
templateId: process.env.ADMIN_SPEAKER_EMAIL_TEMPLATE,
dynamic_template_data: {
emailContent: emailContent,
sdjsBtn: false,
title: 'SDJS Meetup Speaker Request'
}
}
sgMail.send(email)
.then(() => resolve({ email }))
.catch(err => {
console.log(err);
reject(err);
});
})
}
in conclusion I have no clue what part of talkSubmit is throwing those two errors and yet both emails are getting automatically sent and the store is updating with all the proper data despite the initial action creator returning rejected. I appreciate any help anyone can offer.
Ok so I think the main problem is here:
axios.get(`https://api.meetup.com/sandiegojs/events?no_later_than = ${ date } `)
return resolve(response.data.map(event => ({
meetupId: event.id,
name: event.name,
date: event.local_date,
time: event.local_time,
link: event.link,
description: event.description,
})))
it should look like that (I recommend to extract mapping method):
axios.get(`https://api.meetup.com/sandiegojs/events?no_later_than = ${ date} `)
.then( response => resolve(response.data.map(event => ({
meetupId: event.id,
name: event.name,
date: event.local_date,
time: event.local_time,
link: event.link,
description: event.description,
}))))
.catch(err => reject(new Error('getMeetups failed to get SDJS meetups')))
and a few words about Promises. You can chain them like that:
method()
.then(method2())
.then(method3())
.then(method4())
...
.catch(err =>...
also I don't understand why you wrap content of method in return new Promise((resolve, reject) => { I think is not needed in your case
so you can change talkSubmit method to something like that (this is just a draft, I recommend to extract methods from then blocks)
function talkSubmit(speakerInfo, talkInfo, date) {
const { Talk, Speaker, Event } = app.models;
return getMeetups()
.then(meetups => {
const index = meetups.findIndex((item) => item.date == date);
let name = meetups[index].name;
let details = meetups[index].description;
let meetupId = meetups[index].meetupId;
if (index === -1)
return reject(new Error('NO meetup with that date found!'));
return Promise.all([
Event.findOrCreate({
date, name, details,
meetupId
}),
Speaker.create(speakerInfo)])
})
.then(([event, speaker]) => {
let eventId = event[0].id
let speakerId = speaker.id
return Talk.create({
...talkInfo,
speakerId, eventId
})
})
}

Resources