Home > Mobile >  Nested map function resulting in a TypeError after finishing execution
Nested map function resulting in a TypeError after finishing execution

Time:05-17

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:

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

how do I fix it?

CodePudding user response:

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)))
    })})
  • Related