R
R
rodgi2020-05-16 17:34:02
JavaScript
rodgi, 2020-05-16 17:34:02

"UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined", what to do?

Code for getting information about the number of subscribers on YouTube. The code:

const { api_key, channel_id } = "./config.json"
const fetch = require('node-fetch')
const livesubs = () => {
    let response = fetch(`https://www.googleapis.com/youtube/v3/channels?part=statistics&id=${channel_id}&key=${api_key}`)
        .then(response => response.json())
        .then(function (response) {
            updateView(response.items[0].statistics.subscriberCount);
        })};
     const updateView = (subscribersCount) => {
        counterValue.innerHTML = subscribersCount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    };
    function app() {
        livesubs();
        window.setInterval(livesubs, 5000);
     }

Error: UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mitya_k, 2020-05-16
@mitya_k

Add catch

.then(function (response) {
            updateView(response.items[0].statistics.subscriberCount);
        })..catch(err => console.log(err))

In general, you are apparently referring to a structure that is not an array. Do console.log(response.items)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question