Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested map function resulting in a TypeError after finishing execution

code:

window.reddit.comments("uq0mzi").sort('hot').fetch(function(res) {
 res[1].data.children.flatMap((item) => {
      console.log(item.data.body)
      item.data.replies.data.children.map(y => (y.data.body === undefined ? "" : console.log(" >>>"+y.data.body)))
 })})

what I’m trying: I’m using the reddit API wrapper to get comments and their replies of a post. first map prints out the top level comments, while the second map is supposed to print out the replies to those comments

where its going wrong: the code works, but after printing everything, I’m getting a type error saying:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught TypeError: Cannot read properties of undefined (reading ‘children’)

how do I fix it?

>Solution :

My favorite solution is to use getSafe function to avoid undefined errors.

If the value is undefined, a default value will be returned instead of undefined

const getSafe = (fn, defaultVal) => {
    try {
        if (fn() === undefined || fn() === null) {
            return defaultVal
        } else {
            return fn();
        }

    } catch (e) {
        return defaultVal;
    }
}

window.reddit.comments("uq0mzi").sort('hot').fetch(function(res) {
    res[1].data.children.flatMap((item) => {
         console.log(item.data.body)
         getSafe(()=>item.data.replies.data.children, []).map(y => (y.data.body === undefined ? "" : console.log(" >>>"+y.data.body)))
    })})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading