I am writing a CLI command where I’m taking input as coin name and currency from user. But when I’m assigning my input variable it’s throwing error. See code first.
I tried Hardcoding instead of doing this res.data.data.coinOption; I did this res.data.data.BTC (Hardcoding);
import axios from "axios";
import colors from "colors";
class CryptoAPI {
constructor(apikey) {
this.apikey = apikey;
this.baseUrl =
"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest";
}
async getPriceData(coinOption, curOption) {
try {
const res = await axios.get(
`${this.baseUrl}?symbol=${coinOption}&convert=${curOption}`,
{
headers: {
"X-CMC_PRO_API_KEY": this.apikey,
},
}
);
let coinData = res.data.data.coinOption;
let output = `Coin : ${coinData.symbol} (${coinData.name}) | Price : ${coinData.quote.INR.price} | Rank : ${coinData.cmc_rank} | Change 24H : ${coinData.quote.INR.percent_change_24h}%`;
return output;
} catch (error) {
console.log(error);
}
}
}
export default CryptoAPI;
Error
TypeError: Cannot read properties of undefined (reading 'symbol')
at CryptoAPI.getPriceData (file:///C:/Users/***/node.js/Projects/Coindex-CLI/lib/cryptoAPI.mjs:23:39)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.price (file:///C:/Users/***/node.js/Projects/Coindex-CLI/commands/check.mjs:12:31)
undefined
I’m expecting that coinOption carry the input (BTC,ETH,XRP etc) and when I’m putting this variable i n the response data data.coinOption.name i will get “Bitcoin” but it doesn’t happening and in order to get name I’m Hard coding data.BTC.name which is not handy in multiple coins selection
See the data comming from server looks like this For example
"data": {
"BTC": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"num_market_pairs": 11018,
"date_added": "2010-07-13T00:00:00.000Z",
}
]
}
Code Geek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1