Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
can't retrieve data because of 'undefined' value

In my website i am listing movies and tv series that users can share their comments on them. Users can add comments, but when it comes to receiving comments, an undefined value is returned. (I am trying to get comments from movieComment. movieComment store comments for the movie)

var show = qs["movieId"];
/* show variable is giving my movie's ID and it is 1 */
btnComment.addEventListener('click', (e) => {
    var movieComment = document.getElementById('textComment').value;
    push(child(firebaseRef, 'Movies/' + show + '/movieComment/'), movieComment) {
        movieComment: movieComment
    };
});

function AddItemsToTable2(comment) {
    const comments = `
              <td>Alan Smith</td>
              <td><i class="fa fa-star" style="color:rgb(91, 186, 7)"></i></td>
              <td>${comment}<h6>[May 09, 2016]</h6></td>
            `;
    html = comments;
    body2.innerHTML += html;
}

}

function AddAllItemsToTable2(TheComments) {
    body2.innerHTML = "";
    TheComments.forEach(element => {
        AddItemsToTable2(element.movieComment);
    });
}

function getAllDataOnce2() {
    var show = qs["movieId"];
    get(child(firebaseRef, 'Movies/' + show + '/movieComment')).then((snapshot) => {
        var comments = [];
        comments.push(snapshot.val());
        console.log(comments);
        AddAllItemsToTable2(comments);

    });

}

window.onload = (event) => {
    getAllDataOnce2();

};

enter image description here

Console.log(movies)

enter image description here

Undefined error:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Focusing on this function:

function AddAllItemsToTable2(TheComments) {
    body2.innerHTML = "";
    TheComments.forEach(element => {
        AddItemsToTable2(element.movieComment);
    });
}

The TheComments object here is a Record<string, string>[]:

TheComments = [{
  "-Mstwhft8fKP6-M2MRIk": "comment",
  "-Mstwj5P2TD_stgvZL8V": "a comment",
  "-MstwjxvmkNAvWFaIejp": "another comment"
}]

When you iterate over this array, you end up with an element object that doesn't have a movieComment property, which is why when you feed it to AddItemsToTable2 you get undefined.

To fix this, you need to change the way you assemble the TheComments object:

function AddAllItemsToTable2(TheComments) { // TheComments: ({id: string, text: string})[]
    body2.innerHTML = "";
    TheComments.forEach(commentObj => AddItemsToTable2(commentObj.text));
}

function getAllDataOnce2() {
    const show = qs["movieId"];
    get(child(firebaseRef, 'Movies/' + show + '/movieComment'))
        .then((snapshot) => {
            const comments = [];
            snapshot.forEach(childSnapshot => {
                comments.push({
                    id: childSnapshot.key,     // store this for linking to database/anchors
                    text: childSnapshot.val()
                });
            });
            console.log(comments);
            AddAllItemsToTable2(comments);
        });
}

As another point, beware of XSS risks when using innerHTML and use innerText where possible for any user generated content. Also, you should wrap your comment content in a table row so comments are concatenated properly.

function AddItemsToTable2(commentObj) {
    const commentEle = document.createElement('span');
    commentEle.id = `comment_${commentObj.id}`;
    commentEle.innerText = commentObj.text;
    
    const commentRowHTML = `
            <tr>
              <td>Alan Smith</td>
              <td><i class="fa fa-star" style="color:rgb(91, 186, 7)"></i></td>
              <td>${commentEle.outerHTML}<h6>[May 09, 2016]</h6></td>
            </tr>`;
    body2.innerHTML += commentRowHTML;
}

function AddAllItemsToTable2(TheComments) {
    body2.innerHTML = "";
    TheComments.forEach(commentObj => AddItemsToTable2(commentObj));
}

With the above code block, you can now add #comment_-MstwjxvmkNAvWFaIejp to the end of the current page's URL to link to the "another comment" comment directly similar to how StackOverflow links to comments.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda