I have an interaction handler that shows a name of a user stored in mongodb one at a time from a click on a button component. There are two buttons, first user and second user, some sort of pagination. My problem is that the users array that received values from push on the first user button returns empty when called on the second user button.
The array does receive values just fine, but it really is empty when I check the value of users on console on the second button interaction (returns []).
So my question is how can I use the global array that received values from .push on my other interaction check conditions?
client.on("interactionCreate", async (interaction) => {
let page = 0;
let users = [];
if (interaction.customId === "firstUserBtn") {
db.collection("users")
.find()
.forEach((user) => users.push(user))
.then(() => {
const name = users[page].name;
console.log(name);
});
}
if (interaction.customId === "secondUserBtn") {
page = 1;
const name = users[page].name;
console.log(name);
}
});
CodePudding user response:
Global array returns empty with values from .push
The users
array isn't global, it's a local created every time the client.on
callback is run. That means that the array that gets values added to it when interaction.customId === "firstUserBtn"
is a different array than the one you're looking at later when interaction.customId === "secondUserBtn"
.
If you want to use the same array, move users
out of the callback (you probably want to move page
as well):
let users = []; // <==============================================
let page = 0; // <==============================================
client.on("interactionCreate", async (interaction) => {
if (interaction.customId === "firstUserBtn") {
db.collection("users")
.find()
.forEach((user) => users.push(user))
.then(() => {
const name = users[page].name;
console.log(name);
});
}
if (interaction.customId === "secondUserBtn") {
page = 1;
const name = users[page].name;
console.log(name);
}
});