Closed CleitonRReis closed 2 years ago
Olá @CleitonRReis!
Dá uma olhada neste vídeo.
Como vc viu, eu não encontrei comportamento inesperado na renderização dos dados. Vc pode explicar melhor qual é o problema?
Ah, se puder, suba o projeto em um repositório no GitHub e envie o link por aqui. Assim fica mais prático eu baixar a aplicação aqui e te ajudar com mais precisão =)
Bom dia, Roger! Tudo bem?
Desde já, obrigado pelo rápido retorno.
Peço desculpas, acredito que não expliquei bem onde está o problema. 😅
O problema citado, acontece quando tento pesquisar por um título de filme - The Batman, por exemplo - perceba que traz resultados, contudo, duplica/triplica...
Estou colocando uma imagem no corpo do e-mail para exemplificar melhor o problema, e também subi o código para um repo como você pediu.
Link repositório: https://github.com/CleitonRReis/appflix-js [https://opengraph.githubassets.com/80690e4489bdd6ea7ea04c70278cbd7f236b5b3726544641f3fb25cb40e44656/CleitonRReis/appflix-js]https://github.com/CleitonRReis/appflix-js GitHub - CleitonRReis/appflix-jshttps://github.com/CleitonRReis/appflix-js Contribute to CleitonRReis/appflix-js development by creating an account on GitHub. github.com
[cid:008d945c-ccf0-4d5e-8ed3-fa261703637d]
De: Roger Melo @.> Enviado: quinta-feira, 28 de abril de 2022 22:53 Para: roger-melo-treinamentos/curso-de-js-roger-melo @.> Cc: Cleiton Reis @.>; Mention @.> Assunto: Re: [roger-melo-treinamentos/curso-de-js-roger-melo] Dúvida sobre Filtro (Issue #3508)
Olá @CleitonRReishttps://github.com/CleitonRReis!
Dá uma olhada neste vídeohttps://drive.google.com/file/d/1sJc7ksjINlyCFUyZVJzZ9awaqltgmWwQ/view?usp=sharing.
Como vc viu, eu não encontrei comportamento inesperado na renderização dos dados. Vc pode explicar melhor qual é o problema?
Ah, se puder, suba o projeto em um repositório no GitHub e envie o link por aqui. Assim fica mais prático eu baixar a aplicação aqui e te ajudar com mais precisão =)
— Reply to this email directly, view it on GitHubhttps://github.com/roger-melo-treinamentos/curso-de-js-roger-melo/issues/3508#issuecomment-1112809608, or unsubscribehttps://github.com/notifications/unsubscribe-auth/APDQZINBOJISAHSNZDD5IOTVHM6JDANCNFSM5UQHWN7A. You are receiving this because you were mentioned.Message ID: @.***>
@CleitonRReis agora ficou mais claro, hahah
Antes de responder, deixa eu dar uma dica...
Quando possível, prefira acessar a issue no repositório, ao invés de acessar por email. Email não é capaz, por exemplo, de renderizar código com syntax-highlight como aqui nos comentários das issues.
Ao invés de dar a resposta pronta, vou mostrar o caminho, ok? =)
No exemplo abaixo, eu apenas inseri uma ul
como primeira filha do body e deixei apenas o essencial da lógica de exibição dos filmes no js:
<body>
<ul data-js="ul"></ul>
<!-- ... -->
</body>
const ul = document.querySelector('[data-js="ul"]')
const showMoviesList = async e => {
e.preventDefault()
const inputValue = e.target.value.trim().toLowerCase()
const response = await fetch(searchFilm(inputValue))
const { results } = await response.json()
const lis = results.map(result => `<li>${result.title}</li>`).join('')
ul.innerHTML = lis
}
filterInput.addEventListener('input', showMoviesList)
Ao inserir "The Batman" no input (digitando cada caractere), as li
s dos filmes não se repetiram...
Bom dia, Roger! Tudo bem?
Muito obrigado pela ajuda. Conforme imagem em anexo, consegui passar para o código a sua ideia e acabou que deu certo.
Lhe dizer porquê de os filmes não estarem duplicando, eu não sei. Da mesma forma que não sei dizer porquê na primeira solução estavam. 😑
Se você puder esclarecer ambas as dúvidas, lhe agradeço muito. Ou seja, gostaria de saber o motivo de na solução inicial estarem duplicado/triplicando... e entender de agora, com a nova solução, não acontecer o erro.
Desde já, agradeço demais! Abs!
A resposta está aqui:
ul.innerHTML = lis
Na linha acima, a cada execução da função showMoviesList
(executada a cada mudança de valor no input), a ul
está sofrendo uma reatribuição. Isso significa que as antigas lis serão descartadas e substituídas pelas novas lis que o map gerou.
As novas lis contém o resultado da API. Esse resultado da API não vêm duplicado/triplicado. Experimente inserir um console.log(results)
antes da const lis e vc irá comprovar isso.
Então, provavelmente, no seu código, o que estava duplicando os filmes é que ao invés de fazer a ul receber apenas as novas lis, as lis antigas também estavam sendo inseridas na ul.
Ficou mais claro?
@CleitonRReis
Boa tarde, Roger! Tudo bem?
Obrigado pelo retorno. Ficou claro, sim. Como sempre você ajudou muito!
Abs!
Show. No que precisar, é só abrir uma nova issue =)
Etapa da aula
9
Nome da aula
Buscando e filtrando to-dos - Aula 02-03
Link da aula
https://app.nutror.com/v3/curso/a977a43d31cedcb6e7d064649ddd6c5436155aaf/curso-de-javascript-roger-melo/aula/1073158
Descreva a dúvida
Fala, Roger! Blz?
Minha dúvida não é referente a aula em si, mas sim sobre um projeto que estou desenvolvendo para treinar os conhecimentos.
Estou tentando implementar um filtro nos dados que vem da API TMDB, com base na aula citada acima. O filtro acontece, contudo, quando os dados são renderizados na tela, eles acabam duplicando, triplicando e assim vai...
Pensei em anexar uma imagem com os dados renderizados em tela, mas acho que não é possível.
Minha dúvida é: O que eu posso fazer para que os dados que vem da API sejam renderizados apenas uma vez?
Desde já agradeço.
***OBS: Desculpe colocar tanto código.
Abaixo está o código desenvolvido até o momento:
Já tentei resolver de algumas formas, mas
@Roger-Melo