I am currently making the shop for my bot, and I am doing the buy command. I have decided to store the user's inventory as an object in the database, however, when I first try to buy and item from the shop (in this case, the fan), it makes the (blank) object, but then it returns:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fan' of undefined
Here is the code: https://github.com/boomermath/grapeoverhaul/blob/master/commands/t.js
module.exports = {
name: 't',
description: 'dig to earn stars',
cooldown: 0,
execute(message, args, d) {
//blank object to initialize in the db
const blankObj = {}
//items in the shop and their cost
const itemCost = {
fan: 100,
orangedetector: 100,
mangodetector: 50,
carrotdetector: 50,
starmagnet: 100,
starmill: 400
}
async function buy() {
//get person's inventory
let have = await d.items.get(message.author.id);
//if they arent in the db, initialize
if (have === undefined || have === null) {
await d.items.set(message.author.id, blankObj)
}
//argument parsing, get item and number of items user wants
let regex = /\d+/g;
let numberOfItemsRaw = args.join(' ').match(regex);
let numberOfItems = parseInt(numberOfItemsRaw);
let item = args.join(' ').replace(numberOfItems, '').replace(' ', '');
//if they don't specify a number assume one.
if (numberOfItemsRaw === NaN || numberOfItemsRaw === null || numberOfItemsRaw === undefined) {
numberOfItems = 1;
}
//because some idot is gonna put 0, i guarantee it
if (numberOfItems === 0) {
message.channel.send('ok karen');
return;
}
//if item is not in the shop, then big oof
if (!Object.keys(itemCost).includes(item)) {
message.channel.send("dude that's not an item in the shop");
return;
}
//total cost
let total = itemCost[item] * numberOfItems;
//if ur broke
if (total > await d.users.get(message.author.id)) {
message.channel.send('you donut have enough money, rip');
return;
}
//take money
d.addMoni(message.author.id, -total)
//intialize item property to store item
if (have[item] === undefined || have[item] === null) {
have[item] = 0;
}
//give item(s)
have[item] += numberOfItems
//put in db
d.items.set(message.author.id, have);
message.channel.send(item);
message.channel.send(numberOfItems);
}
buy();
}
};
How do I fix it so it doesn't return an undefined error?
You forgot to initialize
have
whenawait d.items.get(message.author.id)
is null or undefined.So that
have
won't beundefined
when you try to evaluatehave[item]
.