Avoiding Overwriting Variables in Collectors (14.14.1)

When using collectors, what is the best way to preserve a variable determined in one interaction for use in a future interaction on the same message? For example, I'm making an rpg bot that first asks which stat you're rolling with, and then which modifiers apply. If I assign the stat value to a variable, that variable gets overwritten if a second person uses the command before the first person finishes, and they both wind up rolling whichever stat was selected second. What is the best way to tie the stat to the specific message being interacted with, such that no overwriting occurs when multiple people are using the same command at the same time? Code snippet:
const reply = await interaction.reply({content: 'Choose a stat to roll with!', components: [buttonRow0]});

const filter = (i) => i.user.id === interaction.member.id;

const collector = reply.createMessageComponentCollector({
componentType: ComponentType.Button,
filter
});

stat = ''; // Unsure if I should initialize stat here or elsewhere, right now it's being overwritten
collector.on('collect', async (interaction) => {
if(interaction.customId.startsWith('rollStat')) {
stat = await this.CheckTalents(interaction); // Method that edits message to check for modifiers
return;
}
else if(interaction.customId.startsWith('rollTalent'))
{
await this.Roll(interaction, stat); // Final rolling with stat and modifiers
return;
}
});
const reply = await interaction.reply({content: 'Choose a stat to roll with!', components: [buttonRow0]});

const filter = (i) => i.user.id === interaction.member.id;

const collector = reply.createMessageComponentCollector({
componentType: ComponentType.Button,
filter
});

stat = ''; // Unsure if I should initialize stat here or elsewhere, right now it's being overwritten
collector.on('collect', async (interaction) => {
if(interaction.customId.startsWith('rollStat')) {
stat = await this.CheckTalents(interaction); // Method that edits message to check for modifiers
return;
}
else if(interaction.customId.startsWith('rollTalent'))
{
await this.Roll(interaction, stat); // Final rolling with stat and modifiers
return;
}
});
3 Replies
d.js toolkit
d.js toolkit4mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button! - Marked as resolved by OP
duck
duck4mo ago
If I assign the stat value to a variable, that variable gets overwritten if a second person uses the command before the first person finishes, and they both wind up rolling whichever stat was selected second
sounds more like a scoping issue than anything djs related
Ferretsroq
Ferretsroq4mo ago
Wow, that's embarrassing haha. It seems to be working fine now, thank you.