0

So I have a discord command that scrapes the inventory of a website, but whenever a website doesn't have any stock for the item, it returns undefined. How would I replace "undefined" to "Out Of Stock". I've tried if(variant.inventory_quantity == undefined) { let updatedStock = variant.inventory_quantity.replace("undefined", "Out Of Stock")}, but when the command executes, it returns Error reading undefined ".replace()". I've also tried "if(variant.inventory_quantity == undefined) { let stock = variant.inventory_quantity.toString() let updatedStock = stock .replace("undefined", "Out Of Stock")}, but I get the error "Error reading undefined ".toString()". Does anyone have any ideas?

        axios.get(`${newLink}.json`).then((response) => {

            if (response.data.product.variants) {
                const { product } = response.data
                let productName = product.title
                atcEmbed.setColor("#2B2F51")
                atcEmbed.setTitle(`Product Found! `)
                atcEmbed.setURL(link)
                atcEmbed.setThumbnail(product.images[0].src)
                product.variants.forEach((variant) => {
                    let cleanlink = link.split('?').toString()
                    let partarr = cleanlink.split("/")
                    cleanlink = partarr.slice(0,3).join('/')
                    var updatedLink = cleanlink + "/cart/" + variant.id + ":1".toString()
    
                    atcEmbed.setDescription(`**Product:** ${productName}\n**Price:** ${variant.price}\n**SKU:** ${variant.sku}`)
                    atcEmbed.addFields({ name: `${variant.title}`, value: `[ATC](${updatedLink})\n**Stock:** ${variant.inventory_quantity}\n${variant.id}`, inline: true })
                })
JediSZN
  • 59
  • 6
  • Please provide more code, we are not even seeing the declaration of "productName". – Dan Jan 16 '23 at 16:58
  • 3
    `undefined` is not a string, so `if(variant.inventory_quantity == undefined) { let updatedStock = variant.inventory_quantity.replace("undefined", "Out Of Stock")}` will not work since there is no string to replace within. You could possibly do `if(variant.inventory_quantity == undefined) { let updatedStock = "Out Of Stock"}` – mykaf Jan 16 '23 at 17:10
  • You simply want `variant.inventory_quantity ?? "Out of stock"`. – Bergi Jan 16 '23 at 17:24

0 Answers0